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.
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.
String object has index values from 0 to one less than the length of the string.| Method | Returns | Example on "sandwich" | Result |
|---|---|---|---|
int length() | Number of characters | food.length() | 8 |
String substring(int from, int to) | Characters from index from to to − 1 | food.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 −1 | food.indexOf("wi") | 4 |
boolean equals(Object other) | true if same sequence of characters | food.equals("Sandwich") | false |
int compareTo(String other) | < 0, 0, or > 0 by alphabetical order | food.compareTo("soup") | negative |
Measuring a String
Predict the output.
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());
8
s
h
0
- 1
length()counts the characters: 8. - 2First character.
substring(0, 1)is the single character at index 0: "s". - 3Last character. The last index is
length() - 1= 7, andsubstring(7)runs to the end: "h". - 4The empty string has length 0 and no valid indices at all.
length() - 1.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).
substring(from, to) returns the characters from index from through index to - 1.Both Forms of substring
Predict each result.
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) + "]");
wich
sand
ndw
[]
[]
- 1
substring(4)runs from index 4 to the end: "wich". - 2
substring(0, 4)takes indices 0 to 3: "sand". - 3
substring(2, 5)takes indices 2, 3, 4: "ndw" (Figure 2). - 4Equal arguments give the empty string:
substring(3, 3)has length 3 − 3 = 0. - 5
substring(8)is allowed because 8 equalslength(): it returns the empty string.
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.
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"));
o
b
t
true
- 1Index 0.
substring(0, 1)is "o". - 2Index 2.
substring(2, 3)is "b". - 3Last index.
substring(4, 5)is "t". - 4Comparing one character. The result is a
String, so compare it withequals.
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) | No | StringIndexOutOfBoundsException |
substring(-1, 2) | No | StringIndexOutOfBoundsException |
substring(2, 1) | No | StringIndexOutOfBoundsException (from > to) |
Asking for Characters That Are Not There
Which call fails, and why?
String pet = "cat";
System.out.println(pet.substring(1, 3));
System.out.println("[" + pet.substring(3) + "]");
System.out.println(pet.substring(2, 4));
- 1
substring(1, 3). Indices 1 and 2: "at". Valid, because the ending index may equal the length. - 2
substring(3). Starting at the length gives the empty string: "[]". - 3
substring(2, 4). The ending index 4 is greater than the length 3, so Java throws aStringIndexOutOfBoundsExceptionand the program stops.
StringIndexOutOfBoundsException. Attempting to access indices outside the string results in this exception."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.
indexOf(str) returns the index of the first occurrence of str, or −1 if it is not found.Searching a String
Predict each result.
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"));
2
1
8
-1
-1
- 1
"ss". The first match starts at index 2; the later one at 5 is ignored. - 2
"i". First found at index 1. - 3
"ppi". Starts at index 8. - 4
"q". Not present: −1. - 5
"Miss". Searches are case-sensitive; "M" does not match "m", so −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.
Comparing Characters, Not References
Predict each result.
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);
true
false
false
- 1
a.equals(c). Same sequence of characters:true, even thoughcis a separate object. - 2
a.equals(b). "L" and "l" differ, sofalse. Comparisons are case-sensitive. - 3
a == c. Different objects, so the references differ:false.
equals to compare the characters of two strings; == only tests whether they are the same object.== 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.
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.| Comparison | Result | Meaning |
|---|---|---|
"apple".compareTo("banana") | negative | "apple" comes first |
"cat".compareTo("car") | positive | "cat" comes after "car" |
"car".compareTo("carpet") | negative | A prefix comes before the longer string |
"cat".compareTo("cat") | 0 | Equal |
Ordering Strings
Predict each result. Focus on the sign.
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);
-1
2
0
-3
true
- 1"apple" vs "banana". The first letters differ, "a" before "b": a negative value.
- 2"cat" vs "car". The first difference is at index 2: "t" comes after "r", so the value is positive.
- 3"cat" vs "cat". Equal: 0.
- 4"car" vs "carpet". "car" is a prefix of "carpet", and the shorter string comes first: negative.
- 5Using the sign.
compareTo(...) < 0istrueexactly when the first string comes first. Rely on the sign, not the particular number.
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.
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.
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);
08 | 45
525
- 1Find the separator.
indexOf(":")is 2. - 2Before it.
substring(0, 2)is "08". - 3After it.
substring(3)is "45". - 4Convert and compute. 8 × 60 + 45 = 525.
indexOf and cutting around it with substring is a pattern used constantly with text.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.
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).