AP® Computer Science A review sheet from Aim for Five (aimforfive.com/csa/units/1/1-15)
Unit 1 · Topic 1.15
1.15 String Manipulation
Strings are the objects you'll use most, and almost every free-response question touches them. You need to know exactly what substring, indexOf, equals and compareTo return, how indexes work, and why changing a string really means making a new one.
Key terms
- immutable
- concatenation
- index
substringindexOfequalsandcompareTo
String objects
A String is an object that holds a sequence of characters. You can create one with a literal, like "hello", or with the constructor, new String("hello"). String is in java.lang, so no import is needed.
Strings are immutable: once a String object exists, its characters can never change. Methods like substring don't change the original. They return a brand-new string. To keep the result, you must store it, often back in the same variable: name = name.substring(1);.
Concatenation
The + and += operators join, or concatenate, strings into a new string. If one side of + is a string, the other side is converted to a string automatically, whether it's a number, a boolean or an object. An object is converted by calling its toString method, which every class inherits from Object. Many classes override toString: they replace the inherited version with their own method that has the same signature, so the text describes that object. That's why printing an ArrayList shows its elements in square brackets. You won't write your own toString on the exam.
+ works left to right, which leads to a classic trap:
System.out.println("Sum: " + 2 + 3);
System.out.println(2 + 3 + " is the sum");
System.out.println("Sum: " + (2 + 3));
The first line prints Sum: 23: the string comes first, so 2 and then 3 are each tacked on as text. The second prints 5 is the sum, because 2 + 3 is added as numbers before any string appears. The third uses parentheses to force the addition and prints Sum: 5.
Indexes
Each character has an index, its position, starting at 0. In "computer", c is at index 0 and r is at index 7. The valid indexes run from 0 to length() - 1. Using an index outside that range throws a StringIndexOutOfBoundsException.
There's no method on the Quick Reference that gives you a single character, so you take a one-letter substring: s.substring(i, i + 1) is the character at index i, as a String.
The String methods you need
| Method | What it returns | Example with s = "banana" |
|---|---|---|
| length() | the number of characters | 6 |
| substring(from, to) | characters from index from up to but not including to | s.substring(1, 3) is "an" |
| substring(from) | everything from index from to the end | s.substring(4) is "na" |
| indexOf(str) | index of the first match of str, or -1 if there is none | s.indexOf("an") is 1 |
| equals(other) | true if both have exactly the same characters | s.equals("Banana") is false |
| compareTo(other) | negative if s comes first alphabetically, 0 if equal, positive if later | s.compareTo("cherry") is negative |
Edge cases worth knowing
substring(from, to) gives to - from characters. to may equal length(), and substring(length()) is the empty string "", not an error. Going past length() is an error.
Compare strings with equals, not ==. == checks whether two variables refer to the same object (2.6), so two separately created strings with the same letters can make == false while equals is true. With compareTo, rely only on the sign of the result, not its exact value. Java puts every uppercase letter before every lowercase one, so "Zoo".compareTo("apple") is negative. Watch for that when words mix capital and small letters.
Worked examples
Try each one yourself first, then open the solution.
- Example 1
substring and indexOf
What does this code print?
String word = "computer"; String part = word.substring(3, 6); int spot = word.indexOf("t"); System.out.println(part + spot); System.out.println(word.substring(spot) + word.length());Show the solutionHide the solution
- Step 1: Index the word: c=0, o=1, m=2, p=3, u=4, t=5, e=6, r=7. Its length is 8.
- Step 2:
word.substring(3, 6)takes indexes 3, 4 and 5 (stopping before 6):"put". - Step 3:
word.indexOf("t")finds the first t at index 5. - Step 4:
part + spotis"put" + 5, which is"put5". - Step 5:
word.substring(5)is everything from index 5 on:"ter". Joined withword.length(), 8, that's"ter8".
Answer: Two lines:
put5, thenter8. - Example 2
Building a new string
This code swaps the first and last letters of
s. What is printed?String s = "stone"; String t = s.substring(s.length() - 1) + s.substring(1, s.length() - 1) + s.substring(0, 1); System.out.println(t);Show the solutionHide the solution
- Step 1:
sis"stone", with s=0, t=1, o=2, n=3, e=4. Its length is 5. - Step 2:
s.substring(s.length() - 1)iss.substring(4), the last letter:"e". - Step 3:
s.substring(1, s.length() - 1)iss.substring(1, 4), the middle:"ton". - Step 4:
s.substring(0, 1)is the first letter:"s". - Step 5: Joined:
"e" + "ton" + "s". The originalsis unchanged, since strings are immutable.
Answer: It prints
etons. - Step 1:
Common mistakes
- Thinking
substring(a, b)includes indexb. It stops just before it. - Calling a method on a string and not storing the result, like
name.substring(1);by itself. The original string doesn't change. - Comparing strings with
==. Useequalsfor same characters, orcompareTofor alphabetical order. - Using
length()as a valid index. The last index islength() - 1.
On the exam
- The Methods and Control Structures free-response question has a part that needs
Stringmethods. Practicesubstring(i, i + 1)for single letters andindexOfreturning -1 for "not found". - For tracing questions, write the string out with its indexes underneath before you work out any
substringcall.
Connected topics
Videos
Check yourself
4 questions on 1.15 String Manipulation. Pick an answer to see if you got it, and why.
Consider the following code segment.String s = "computer";
System.out.println(s.substring(2, 5));What is printed as a result of executing the code segment?
Consider the following code segment.String s = "banana";
System.out.println(s.indexOf("an") + " " + s.indexOf("nab"));What is printed as a result of executing the code segment?
Consider the following code segment.String name = "Grace";
name.substring(1);
String upper = name + "!";
System.out.println(name + " " + upper);What is printed as a result of executing the code segment?
Consider the following code segment.String a = new String("hi");
String b = new String("hi");
System.out.println((a == b) + " " + a.equals(b));What is printed as a result of executing the code segment?
0 of 4 answered