AP Computer Science A · Study guide

String Methods

AP® Computer Science A · Using Objects and Methods

String Methods

The String methods every Java programmer uses: length, both forms of substring, indexOf, equals, and compareTo, with exact index rules, the out-of-bounds exception, and patterns for combining them.

Big Picture

A String object has index values from 0 to one less than its length; any attempt to use an index outside that range results in a StringIndexOutOfBoundsException. Six methods cover nearly everything: length() counts characters, substring(from, to) and substring(from) extract pieces, indexOf(str) searches, equals(other) tests for the same characters, and compareTo(other) puts strings in alphabetical order. None of them change the string they are called on.

1Indices and length

Each character in a string has a position, called its index. Indices start at 0: in "sandwich", "s" is at index 0, "a" at index 1, and "h" at index 7. A String object has index values from 0 to one less than the length of the string, so the last index is always length() - 1.

int length() returns the number of characters in a String object, counting every space and punctuation mark. The empty string "" has length 0 and no valid indices. Attempting to access indices outside the range 0 to length() - 1 will result in a StringIndexOutOfBoundsException, a run-time error that stops the program.

The difference between "the length is 8" and "the last index is 7" is the source of many off-by-one errors. Whenever you compute an index, check it against both ends of the valid range.

Figure 1. A String object has index values from 0 to one less than the length of the string.
MethodReturnsExample on "sandwich"Result
int length()Number of charactersfood.length()8
String substring(int from, int to)Characters from index from to to − 1food.substring(0, 4)"sand"
String substring(int from)Same as substring(from, length())food.substring(4)"wich"
int indexOf(String str)Index of first occurrence, or −1food.indexOf("wi")4
boolean equals(Object other)true if same sequence of charactersfood.equals("Sandwich")false
int compareTo(String other)< 0, 0, or > 0 by alphabetical orderfood.compareTo("soup")negative
Worked Example 1 length and indices

Measuring a String

Predict the output.

Code
String food = "sandwich";
System.out.println(food.length());
System.out.println(food.substring(0, 1));
System.out.println(food.substring(food.length() - 1));
System.out.println("".length());
Output
8
s
h
0
  1. 1length() counts the characters: 8.
  2. 2First character. substring(0, 1) is the single character at index 0: "s".
  3. 3Last character. The last index is length() - 1 = 7, and substring(7) runs to the end: "h".
  4. 4The empty string has length 0 and no valid indices at all.
Result: The output is 8, s, h, and 0. Indices start at 0, so the last character of any non-empty string is at length() - 1.
Common Mistake 1 · Using length() as an Index

The last character of word is at index word.length() - 1, not word.length(). word.substring(word.length(), word.length() + 1) is out of bounds. Use word.substring(word.length() - 1) for the last character.

2substring

String substring(int from, int to) returns the substring beginning at index from and ending at index to - 1. The starting index is included and the ending index is not, so the result always has to - from characters. String substring(int from) returns substring(from, length()): everything from from to the end.

The arguments must satisfy 0 ≤ from ≤ to ≤ length(). Notice that to may equal the length (that is how the last character is included), and from may equal to, giving the empty string. A string identical to the single element at position index can be created by calling substring(index, index + 1).

Figure 2. substring(from, to) returns the characters from index from through index to - 1.
Worked Example 2 substring

Both Forms of substring

Predict each result.

Code
String food = "sandwich";
System.out.println(food.substring(4));
System.out.println(food.substring(0, 4));
System.out.println(food.substring(2, 5));
System.out.println("[" + food.substring(3, 3) + "]");
System.out.println("[" + food.substring(8) + "]");
Output
wich
sand
ndw
[]
[]
  1. 1substring(4) runs from index 4 to the end: "wich".
  2. 2substring(0, 4) takes indices 0 to 3: "sand".
  3. 3substring(2, 5) takes indices 2, 3, 4: "ndw" (Figure 2).
  4. 4Equal arguments give the empty string: substring(3, 3) has length 3 − 3 = 0.
  5. 5substring(8) is allowed because 8 equals length(): it returns the empty string.
Result: The results are wich, sand, ndw, and two empty strings. The ending index is excluded, and a starting index equal to the length is allowed and gives "".
Worked Example 3 Single characters

Extracting One Character at a Time

A string identical to the single character at position index is created by calling substring(index, index + 1). Predict the output.

Code
String word = "orbit";
int i = 2;
System.out.println(word.substring(0, 1));
System.out.println(word.substring(i, i + 1));
System.out.println(word.substring(word.length() - 1, word.length()));
System.out.println(word.substring(1, 2).equals("r"));
Output
o
b
t
true
  1. 1Index 0. substring(0, 1) is "o".
  2. 2Index 2. substring(2, 3) is "b".
  3. 3Last index. substring(4, 5) is "t".
  4. 4Comparing one character. The result is a String, so compare it with equals.
Result: The output is o, b, t, and true. substring(index, index + 1) is the standard way to work with a single character as a String.
Call on "cat" (length 3)Valid?Result
substring(0, 3)Yes"cat"
substring(3)Yes"" (start equals length)
substring(2, 2)Yes""
substring(2, 4)NoStringIndexOutOfBoundsException
substring(-1, 2)NoStringIndexOutOfBoundsException
substring(2, 1)NoStringIndexOutOfBoundsException (from > to)
Worked Example 4 Out of bounds

Asking for Characters That Are Not There

Which call fails, and why?

Code
String pet = "cat";
System.out.println(pet.substring(1, 3));
System.out.println("[" + pet.substring(3) + "]");
System.out.println(pet.substring(2, 4));
  1. 1substring(1, 3). Indices 1 and 2: "at". Valid, because the ending index may equal the length.
  2. 2substring(3). Starting at the length gives the empty string: "[]".
  3. 3substring(2, 4). The ending index 4 is greater than the length 3, so Java throws a StringIndexOutOfBoundsException and the program stops.
Result: The program prints at and [], then stops with a StringIndexOutOfBoundsException. Attempting to access indices outside the string results in this exception.
Common Mistake 2 · Including the Ending Index

"sandwich".substring(2, 5) is "ndw", three characters, not "ndwi". The character at index to is never included. A quick check: the result's length must equal to - from.

3indexOf

int indexOf(String str) returns the index of the first occurrence of str; it returns −1 if str is not found. When str is longer than one character, the result is the index where the match begins. Later occurrences are ignored: "mississippi".indexOf("ss") is 2, even though "ss" also appears at 5.

The search is case-sensitive, so "M" and "m" are different characters. The return value −1 is a signal, not an index; using it as an index in substring causes an exception. Code that uses the result of indexOf should be sure the search text is present.

Figure 3. indexOf(str) returns the index of the first occurrence of str, or −1 if it is not found.
Worked Example 5 indexOf

Searching a String

Predict each result.

Code
String river = "mississippi";
System.out.println(river.indexOf("ss"));
System.out.println(river.indexOf("i"));
System.out.println(river.indexOf("ppi"));
System.out.println(river.indexOf("q"));
System.out.println(river.indexOf("Miss"));
Output
2
1
8
-1
-1
  1. 1"ss". The first match starts at index 2; the later one at 5 is ignored.
  2. 2"i". First found at index 1.
  3. 3"ppi". Starts at index 8.
  4. 4"q". Not present: −1.
  5. 5"Miss". Searches are case-sensitive; "M" does not match "m", so −1.
Result: The results are 2, 1, 8, −1, and −1. indexOf reports where the first match begins, or −1 when there is no match.

4equals

boolean equals(Object other) returns true if the string corresponds to the same sequence of characters as other, and false otherwise. It compares content: two separate String objects with identical characters are equals, even though == would report false because they are different objects.

The comparison is exact and case-sensitive: "Lima" and "lima" are not equal, and neither are "lima" and "lima " with a trailing space. Use equals whenever you mean "do these strings say the same thing?", and always compare a String with another String.

Worked Example 6 equals

Comparing Characters, Not References

Predict each result.

Code
String a = "Lima";
String b = "lima";
String c = new String("Lima");
System.out.println(a.equals(c));
System.out.println(a.equals(b));
System.out.println(a == c);
Output
true
false
false
  1. 1a.equals(c). Same sequence of characters: true, even though c is a separate object.
  2. 2a.equals(b). "L" and "l" differ, so false. Comparisons are case-sensitive.
  3. 3a == c. Different objects, so the references differ: false.
Result: The results are true, false, and false. Use equals to compare the characters of two strings; == only tests whether they are the same object.
Common Mistake 3 · Comparing Strings With ==

== tests whether two references point to the same object. Two strings with identical text can be different objects, so == may report false for strings that look identical. Use equals to compare text.

5compareTo

int compareTo(String other) returns a value less than 0 if the string is less than other, zero if it is equal to other, and a value greater than 0 if it is greater than other. Strings are ordered based upon the alphabet, character by character from the left. The first position where the strings differ decides the result; if one string runs out first, the shorter one comes first.

The particular number returned is less important than its sign. a.compareTo(b) < 0 means a comes before b; a.compareTo(b) > 0 means it comes after; a.compareTo(b) == 0 means the strings are equal. Note that capital letters are ordered before lowercase letters, so "Zebra" comes before "apple"; comparisons are most predictable when the strings use the same capitalization.

Figure 4. a.compareTo(b) returns a negative value if a comes before b, zero if they are equal, and a positive value if a comes after.
ComparisonResultMeaning
"apple".compareTo("banana")negative"apple" comes first
"cat".compareTo("car")positive"cat" comes after "car"
"car".compareTo("carpet")negativeA prefix comes before the longer string
"cat".compareTo("cat")0Equal
Worked Example 7 compareTo

Ordering Strings

Predict each result. Focus on the sign.

Code
System.out.println("apple".compareTo("banana"));
System.out.println("cat".compareTo("car"));
System.out.println("cat".compareTo("cat"));
System.out.println("car".compareTo("carpet"));
System.out.println("apple".compareTo("banana") < 0);
Output
-1
2
0
-3
true
  1. 1"apple" vs "banana". The first letters differ, "a" before "b": a negative value.
  2. 2"cat" vs "car". The first difference is at index 2: "t" comes after "r", so the value is positive.
  3. 3"cat" vs "cat". Equal: 0.
  4. 4"car" vs "carpet". "car" is a prefix of "carpet", and the shorter string comes first: negative.
  5. 5Using the sign. compareTo(...) < 0 is true exactly when the first string comes first. Rely on the sign, not the particular number.
Result: The values are −1, 2, 0, and −3, and the final comparison is true. compareTo orders strings alphabetically; its sign says which comes first.

6Combining String Methods

Real tasks combine these methods. To split text around a separator, find the separator with indexOf, then take the part before it with substring(0, position) and the part after it with substring(position + 1). To work with a single character, use substring(i, i + 1) and compare the result with equals. To convert the extracted digits into numbers, pass them to Integer.parseInt.

Because strings are immutable, every one of these methods leaves the original string unchanged and returns a new value. Store each intermediate result in a well-named variable; this makes the code easy to read and lets you check each step when the result is not what you expect.

Worked Example 8 Combining methods

Splitting a Time Into Hours and Minutes

A time is stored as text in the form "hh:mm". Use indexOf and substring to compute the total number of minutes after midnight.

Code
String time = "08:45";
int colon = time.indexOf(":");
String hoursText = time.substring(0, colon);
String minutesText = time.substring(colon + 1);
int total = Integer.parseInt(hoursText) * 60 + Integer.parseInt(minutesText);
System.out.println(hoursText + " | " + minutesText);
System.out.println(total);
Output
08 | 45
525
  1. 1Find the separator. indexOf(":") is 2.
  2. 2Before it. substring(0, 2) is "08".
  3. 3After it. substring(3) is "45".
  4. 4Convert and compute. 8 × 60 + 45 = 525.
Result: The program prints 08 | 45 and 525. Locating a separator with indexOf and cutting around it with substring is a pattern used constantly with text.
Common Mistake 4 · Using indexOf's −1 as an Index

If the separator is missing, indexOf returns −1, and substring(0, -1) throws a StringIndexOutOfBoundsException. Code that cuts around a separator relies on the precondition that the separator is present.

Four Habits for String Methods

1. Indices 0 to length() − 1

Anything else throws StringIndexOutOfBoundsException.

2. to Is Excluded

substring(from, to) has to − from characters.

3. −1 Means Not Found

indexOf returns the first match or −1.

4. equals and the Sign of compareTo

Compare text with equals; order it by the sign.

Core Synthesis

A String object has index values from 0 to one less than the length of the string; attempting to access indices outside this range results in a StringIndexOutOfBoundsException. length() returns the number of characters; substring(from, to) returns the substring from index from to index to - 1, and substring(from) returns substring(from, length()); indexOf(str) returns the index of the first occurrence of str or −1; equals(other) returns true for the same sequence of characters; and compareTo(other) returns a negative value, zero, or a positive value based on alphabetical order. A string identical to the single element at position index can be created by calling substring(index, index + 1).