Five String methods on the AP® Computer Science A Java Quick Reference, length, substring, indexOf, equals and compareTo, let you measure, cut, search and compare text. Characters are numbered from index 0 to length() - 1, substring(a, b) returns the characters from index a up to but not including index b, and indexOf returns -1 when the text is missing. Test whether two strings match with equals, never ==.
Quick check
After String s = "hat"; s.substring(1); what does s hold?Show answerHide answer
Still "hat". A
Stringnever changes;substringreturns a new string, and this one was not stored.A method has the header int indexOf(String str). What type of value does a call return?Show answerHide answer
An
int: the return type comes just before the method name.If the first character of a string is at index 0, what index is its fourth character at?Show answerHide answer
Index 3. Counting from 0, the first four indexes are 0, 1, 2 and 3.
Know these already? Jump to the practice questions
What you'll be able to do
- State what each of
length,substring,indexOf,equalsandcompareToreturns. - Determine the characters a
substringcall returns from its indexes. - Predict the output of code that chains String method calls.
- Identify calls that throw a
StringIndexOutOfBoundsException. - Explain why
equals, not==, tests whether two strings hold the same characters.
Key terms
Index
The position number of a character in a string, from 0 for the first character to length() - 1 for the last.
- In plain English
- A character's position, counting from zero.
- Don't write
- "The last character of
sis at indexs.length()."
Empty string
The string "" with no characters, whose length is 0.
- In plain English
- Text with nothing in it.
- Don't write
- "
s.substring(2, 2)throws an exception."
Lexicographic order
Dictionary-style order in which strings are compared character by character using each character's code.
- In plain English
- Alphabetical order, except that every capital letter comes before every lowercase letter.
- Don't write
- "
compareToreturns 1 when the first string comes later."
How do length and indexes work?
Take String w = "orbits";:
| Index | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| Character | o | r | b | i | t | s |
w.length() returns 6, the number of characters, so the indexes run from 0 to 5. The last character is always at length() - 1.
All five of these methods are on the Java Quick Reference. The rule that indexes start at 0 is not on it: Learn this.
Check yourself
Show answerHide answer
code.length() returns 6, and the last index is 5.
How does substring choose its characters?
substring has two versions:
substring(a, b)returns the characters at indexesatob - 1. It always hasb - acharacters.substring(a)returns the characters from indexato the end.
With w = "orbits": w.substring(1, 4) keeps indexes 1, 2 and 3, so it is "rbi"; w.substring(4) is "ts". To take the single character at index k, use substring(k, k + 1).
The indexes must satisfy 0 ≤ a ≤ b ≤ length(). Equal indexes, as in w.substring(3, 3), give the empty string, and so does w.substring(6), because 6 is the length. Anything outside that range, such as w.substring(2, 7) or w.substring(-1), throws a StringIndexOutOfBoundsException.
Key idea
substring(a, b) stops just before index b, so it returns b - a characters.
Check yourself
Show answerHide answer
"har": 3 − 0 = 3 characters, at indexes 0, 1 and 2.
How do you search with indexOf?
indexOf(str) returns the index where the first copy of str starts, or -1 if str does not appear. The search is case-sensitive.
| Call | Returns | Why |
|---|---|---|
"tomato".indexOf("to") | 0 | the first "to" starts at index 0 |
"tomato".indexOf("ma") | 2 | t0, o1, m2 |
"tomato".indexOf("To") | -1 | capital T does not match |
indexOf pairs with substring to split text at a marker. With String t = "key=value"; and int eq = t.indexOf("=");, eq is 3, so t.substring(0, eq) is "key" and t.substring(eq + 1) is "value".
When calls are chained, as in t.substring(4).indexOf("u"), the second call runs on the new string "value", so it returns 3: an index in "value", not in t.
Check yourself
Show answerHide answer
indexOfreports only the first place "ban" starts.
How do you compare two strings?
a.equals(b) returns true when both strings hold exactly the same characters, with case counting. a == b asks a different question: do a and b refer to the same object? Two different objects can hold the same characters, so == can give false when equals gives true.
a.compareTo(b) returns an int:
- negative if
acomes beforebin lexicographic order; - 0 if they are equal;
- positive if
acomes afterb.
Java finds the first index where the strings differ and compares those two characters' codes. Every uppercase letter's code is smaller than every lowercase letter's, so "Zoo" comes before "apple". If one string runs out first, as with "car" and "cart", the shorter one comes first.
Check yourself
Show answerHide answer
Negative. The strings first differ at index 1, and "a" comes before "i".
Worked example 1: Trace chained calls
Question: What is printed?
String s = "watermelon";
int k = s.indexOf("e");
String mid = s.substring(k, k + 3);
int n = s.substring(k + 1).indexOf("e");
System.out.println(mid + n + s.length());
What tells you the method
Each line stores the result of a call, so number the characters and trace the variables.
Step 1: Number the characters.
w0, a1, t2, e3, r4, m5, e6, l7, o8, n9.
WhyEvery call here works with indexes, so you need them written out.
Step 2: Trace each variable.
Line Variable Value 2 k3 3 mid"erm" 4 n2 Whysubstring(3, 6)keeps indexes 3, 4 and 5. On line 4,s.substring(4)is "rmelon", and its first "e" is at index 2 of that new string.Step 3: Join the printed parts.
"erm" + 2 is "erm2", and then + 10 (the length) is "erm210".
WhyThe left operand is a
String, so each+joins.
Check it
In s, the second "e" is at index 6, which is 4 + 2: the start of the new string plus n. So n was counted in the new string, as it should be.
Answer
erm210
Worked example 2: Design a method that finds a file extension
Question: A method extension(String fileName) must return the text after the dot. Precondition: fileName contains exactly one dot. Design the method, then state what System.out.println(extension("photo.jpeg")); prints.
What tells you the method
A design task: state the input and output, plan the steps with String methods, then trace the design.
Step 1: Plan.
Input "notes.txt", output "txt". Find the dot with
indexOf("."); the extension starts one index after it and runs to the end.WhyThe dot is the only marker between the name and the extension.
Step 2: Write the body.
public static String extension(String fileName) { int dot = fileName.indexOf("."); return fileName.substring(dot + 1); }WhyThe one-parameter
substringruns to the end, so you don't need the length.Step 3: Trace "photo.jpeg".
dotis 5, so the method returnssubstring(6), which is "jpeg".Whyp0, h1, o2, t3, o4, .5, then j at index 6.
Check it
Test the boundary "readme.", which meets the precondition: dot is 6, the length is 7, and substring(7) returns "" without an exception.
Answer
jpeg
Worked example 3: Choose the comparison
Question: The method isBefore should return true exactly when a comes before b in lexicographic order. Which return statement does this?
- A)
return a.compareTo(b) > 0; - B)
return a < b; - C)
return a.compareTo(b) < 0; - D)
return !a.equals(b);
What tells you the method
A "which statement" question about ordering, so test each option on a pair whose order you know.
Step 1: Pick a test pair.
a= "ant" andb= "bee": "ant" comes first, so the method should returntrue.WhyA known answer shows which options give the right result.
Step 2: Test each option.
"ant".compareTo("bee")is negative, so A givesfalseand C givestrue. B does not compile:<works only on numbers. D givestruefor "ant" and "bee", but also for "bee" and "ant", where it should givefalse.WhyOnly C turns "comes before" into "negative".
Check it
Run C on "bee" and "ant": compareTo is positive, so C gives false, which is correct.
Answer
C
Your turn
Question: What is printed?
String t = "harbor";
System.out.println(t.substring(2, 5) + t.substring(5));
Step 1: Do the first call.
h0, a1, r2, b3, o4, r5, so
substring(2, 5)keeps indexes 2, 3 and 4: "rbo".Step 2: Your go: work out
t.substring(5)and join the two parts.
Show the full solutionHide the solution
Step 2. substring(5) runs from index 5 to the end, which is "r". Joining gives "rbo" + "r", which is "rbor".
Answer: rbor
Traps
Trap
Index positions continue from the original string after a chained call.
It seems right because the characters came from the original. But s.substring(4).indexOf("e") searches the new string, which starts at index 0, so the result is an index in the new string.
What does "pancake".substring(3).indexOf("a") return?
- "pancake".substring(3) is "cake", and its "a" is at index 1.
Trap
Strings with the same characters always give true with ==.
It seems right because == works for int values. But for objects, == compares references, so two separate objects holding "yes" can give false. Use equals to compare characters.
Which expression tests whether answer holds the characters "yes": answer == "yes" or answer.equals("yes")?
answer.equals("yes").
What's examined
On the AP® Computer Science A exam (Unit 1), multiple-choice questions ask what chained String calls return or print, or which call throws an exception. Free-response methods can split or compare strings with these five methods, so off-by-one index errors cost you there too.
Practice questions
- Recall For
String w = "rocket";, which expression evaluates to "ket"?
- A)
w.substring(3, 5) - B)
w.substring(4) - C)
w.substring(2, 5) - D)
w.substring(3)
Show answer
Answer: D. "k" is at index 3, and the one-parameter substring runs to the end.
Why the others are wrong:
- A stops before index 5, so it gives "ke".
- B starts one index late, giving "et".
- C starts one index early and stops early, giving "cke".
- Apply Give the value returned by (a)
"tomato".indexOf("to")and (b)"tomato".indexOf("To").
Show answer
Answer: (a) 0 (b) -1
Marking points:
- (a) "to" first starts at index 0; the later "to" at index 4 is not reported.
- (b) The search is case-sensitive, and "To" never appears.
- Apply What is printed?
String x = "pear";
String y = "peach";
System.out.println(x.compareTo(y) > 0);
System.out.println(x.equals(y.substring(0, 4)));
Show answer
Answer: true then false on the next line.
Marking points:
- The strings first differ at index 3, where "r" comes after "c", so
compareTois positive. y.substring(0, 4)is "peac", which is not "pear".
- Exam-style The method should return the part of an email address after the "@", then a colon, then the part before it:
tidy("sam@mail.com")should return "mail.com:sam". Give the number of the line that stops it working.
1: public static String tidy(String email)
2: {
3: int at = email.indexOf("@");
4: String user = email.substring(0, at);
5: String site = email.substring(at);
6: return site + ":" + user;
7: }
Show answer
Answer: Line 5.
Marking points:
substring(at)starts at the "@" itself, so the method returns "@mail.com:sam".- The fix is
String site = email.substring(at + 1);. Line 4 is already right, becausesubstring(0, at)stops before the "@".
- Exam-style For
String s = "pineapple";, what doess.substring(4).indexOf("p")return?
- A) 1
- B) 5
- C) 0
- D) -1
Show answer
Answer: A. s.substring(4) is "apple", and its first "p" is at index 1.
Why the others are wrong:
- B is the index of that "p" in the original string, not in "apple".
- C is where the first "p" of "pineapple" sits, which is not in "apple".
- D assumes the search fails, but "apple" contains "p".
- Recall Name the exception thrown by
"code".substring(2, 5).
Show answer
Answer: StringIndexOutOfBoundsException
Marking points:
- "code" has length 4, and the second index may be at most the length; 5 is too large.
- Apply Which statement about
"apple".compareTo("Banana")is true?
- A) It is negative, because a comes before b in the alphabet.
- B) It is positive, because every lowercase letter's code is larger than every uppercase letter's.
- C) It is
false, because the two strings are not equal. - D) It is negative, because "apple" is shorter than "Banana".
Show answer
Answer: B. The strings differ at index 0, and lowercase "a" has a larger code than uppercase "B", so "apple" comes after "Banana".
Why the others are wrong:
- A ignores case: Java compares character codes, not letters regardless of case.
- C:
compareToreturns anint, not aboolean;equalsis the method that returnsfalsehere. - D: length matters only when one string is the start of the other.
Key points
Recall, then reveal
Say the main points from memory first, then check them.
Show key pointsHide key points
- Indexes run from 0 to
length() - 1. substring(a, b)keepsb - acharacters, fromaup tob - 1;substring(a)runs to the end.indexOfgives the first index where the text starts, or -1.- A chained call works on the new string, with its own indexes from 0.
- Use
equalsto test for the same characters and the sign ofcompareTofor order.