stringIcon

APCS-A Test Review

String Resources

pinnochio

Unlike Pinocchio, we like Strings! They are so important that we devoted this entire page to them.

One of the best ways to learn a language is to become fluent in the manipulation of String content. Always be on the lookout, however, for methods that already exist, rather than making your own.

Declaring/Initializing/Constructing Strings:
  • Directly Declaring/Initializing:

    String realBoy; //declaration
    //declaration must only happen once per 'scope' block
    realBoy = "Pinocchio"; //initialization
    String conscience = "Jiminy Cricket"; //declaration-initialization combo, most common construct

  • Using a String 'constructor':

    String elderlyCarpenter = new String("Geppetto");
  • Empty vs. null Strings

    String temp = ""; //empty: can be used as a building block
    String badBoy = null; //declared but not initialized;
    /*
    'Holds space' but will throw a 'NULL POINTER EXCEPTION' if you try to use an instance method with it
    */
  • Using a char array as a parameter to an (overloaded) constructor:

    char bug[] = {'J', 'I', 'M', 'I', 'N', 'Y'}; //initializer list
    String bugStr = new String(bug);  //String is NOT a char array!!! 
    
  • From a char:

    char ch = 'x';
    //using an easy 'hack,' almost like a 'cast'
    String hackedLtr = "" + ch; 
    //using various 'Wrapper' classes
    String ltr = String.valueOf(ch);
    String duplicateLtr = Character.toString(ch); 
    
Concatenating Strings:
  • Using the (+) operator:

    String p1 = "Pinocchio";
    String p2 = "Knows Strings!";
    String p3 = p1 + " " + p2;
    
  • Using the concat method:

    String p4 = "When you wish";
    String p5 = " upon a star...";
    String p6 = p4.concat(p5);
    
Beloved String Methods:
Method/Concept Example Output Usage/Comments
  • length()
String whale = "Monstro";
int len = whale.length();
System.out.println(whale + " has " + len + " letters");

'Monstro has 7 letters'

Note that length is a method not an attribute like it is for a primative array!

  • charAt(int ndx)
String phrase = "Pinocchio Knows Strings";
char symbol = phrase.charAt(21);
System.out.println("symbol = " + symbol);

'symbol = g'

Beware of 'zero-based indexing!' The first letter in a String is at an index value of 0.

Note that a char may be concatenated with a String, no problem.

  • indexOf(char ch)
  • indexOf(String str)
  • indexOf(String str, int fromIndex)
String phrase = "Pinocchio Knows Strings";
int ndx = phrase.indexOf("s");
System.out.println("first instance of 's' is at index: " + ndx);
ndx = phrase.indexOf("n", 10);
System.out.println("an instance of 'n' is at index: " + ndx);

'first instance of 's' is at index: 14'

The reverse of charAt. Notice that indexOf is overloaded in that it can take either char or String arguments!

Another parameter signature:
indexOf(int ch, int fromIndex)

This allows you to begin a search starting from fromIndex

If a instance is not found, the method returns a -1

  • lastIndexOf(char ch)
  • lastIndexOf(String str)
String phrase = "Pinocchio Knows Strings";
int ndx = phrase.lastIndexOf("o");
System.out.println("last instance of 'o' is at index: " + ndx);

'last instance of 'o' is at index: 12

Identical in nature to indexOf but in reverse!

  • trim()
String phrase = "    'Spaces are evil!'   ";
String trimmedPhrase = phrase.trim();
System.out.println(trimmedPhrase);

'Spaces are evil!'

Trims away all leading and/or trailing 'whitespace'

Using this method is essential when obtaining input from users!

  • substring(int b)
  • substring(int b, int u)

b: beginning ndx
u: upTo ndx

[b, ∞) or [b, u)

String tenDigits = "0123456789";
String result1 = tenDigits.substring(6);
System.out.println(result1);
String result2 = tenDigits.substring(2, 5);
System.out.println(result2);

'6789'
'234'

Takes a portion of a String; the difficult thing about this overloaded method is that the 2-parameter version goes up to but not including the last index mentioned.

A helpful check: returned substring length: upToNdx - startNdx

  • equals()
//Example 1:
String name1 = new String("Programiz");
String name2 = new String("Programiz");
System.out.println("Check if two strings are equal");
// check if two strings are equal
// using == operator
boolean result1 = (name1 == name2);
System.out.println("Using == operator: " + result1);
// using equals() method
boolean result2 = name1.equals(name2);
System.out.println("Using equals(): " + result2);

//Example 2:
String name1 = new String("Programiz");
String name2 = name1;
System.out.println("Check if two strings are equal");
// check if two strings are equal
// using == operator
boolean result1 = (name1 == name2);
System.out.println("Using == operator: " + result1);
// using equals() method
boolean result2 = name1.equals(name2);
System.out.println("Using equals(): " + result2);
                                            
Example 1:
Check if two strings are equal
Using == operator: false
Using equals(): true
                                            
Example 2:
Check if two strings are equal
Using == operator: true
Using equals(): true
                                            
Moral:

NEVER use == to compare Strings!

Example 1:
2 different memory addresses; == compares memory addresses!

Example 2:
name2 is an alias for name1. Same memory address and therefore same value

This was a nifty example from the internet!

  • compareTo()
  • compareToIgnoreCase()
String hero1 = "Spiderman";
String hero2 = "Antman";
System.out.println(hero1.compareTo(hero2)); // Returns >0 because Spiderman comes after Antman in dictionary

String hulk1 = "hulk smash!";
String hulk2 = "HULK SMASH!";;
System.out.println(hero1.compareToIgnoreCase(hero2)); //same except for casing
                                            

18 (S is 18 steps from A in alphabet)

0

Cool for 'lexicographic' comparisons (alphabetizing)

  • toLowerCase()
  • toUpperCase()
String shout = "Boo!";
shout = shout.toUpperCase();
System.out.println(shout);

String whisper = "Hush!";
whisper = whisper.toLowerCase();
System.out.println(whisper);
                                            

'BOO!'

'hush!'

Java Strings are case-sensitive

  • split(String)
String someAvengersStr = "Thor|Spider-man|Hulk|Dr. Strange";
String avengers[] = someAvengersStr.split("|");
for(String a : avengers) System.out.println(a);
                                            

Thor
Spider-man
Hulk
Dr. Strange

A convenient way to create a primitive array of Strings

  • replace(String, String)
  • replaceAll(String, String)
  • replaceFirst(String, String)

The methods above work with char parameters as well (Yea, overloading!)
It appears that replace and replaceAll are identical, but this should be confirmed

String phrase = "Spaces are Evil!   ";
String sanitizedPhrase = phrase.replace(" ", "-");
System.out.println(sanitizedPhrase);
                                            

'Spaces-are-Evil!---'

Learn more about sanitizing phrases at our Password Peek-a-boo app!
  • Character.isUpperCase(ch)
String x = "AP C Sci"; 
ArrayList<Boolean> casing = new ArrayList<Boolean>();                                              
for(int ndx = 0; ndx < x.length(); ndx++){
    String ltr = x.substring(ndx, ndx+1);
    char ch = x.charAt(ndx);
    if(Character.isUpperCase(ch)) casing.add(true);
    else casing.add(false);
}//end for loop
System.out.println(x);
System.out.println(casing);
                                            

AP Computer Science
[true, true, false, true, false, true, false, false]

Use the Character class's isUpperCase() method on a character to determine its casing status.
  • DecimalFormat
import java.text.DecimalFormat;

double number = 987654.321;
DecimalFormat df = new DecimalFormat("#,###.00");
String formattedNumber = df.format(number);
                                            

987,654.32

Use the DecimalFormat class to create formatted String output.
  • String.valueOf(ch)
  • Character.toString(ch)
String w = "manipulate";
char firstChar = w.charAt(0);
String firstLtr = "" + firstChar; //hack to get char to String
char lastChar = w.charAt(len-1);
String lastLtr = String.valueOf(lastChar); //method way to convert
//another way: 
//String lastLtr = Character.toString(lastChar);
System.out.println("firstLtr, lastLtr = " + firstLtr + ", " + lastLtr);
                                            

firstLtr, lastLtr = m, e

Notice there are several techniques to get the nth letter from a String. Some are 'hacky, ' others are based on class methods from either String or Character classes.
Helpful String Manipulations:

There are additional String Manipulation Methods on our Java Utilities page as well.

User Method Call Code
Get Last Symbol in String
String x = "Hello, World!";
String lastSymbl = lastSymbol(x);
public static String lastSymbol(String str){
    int len = str.length();
    char lastChar = str.charAt(len-1);
    return String.valueOf(lastChar);
}//end lastSymbol

Could easily overload this to return a last char
Draw pictures to identify correct character location