Skip to main content

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
  • substring
  • indexOf
  • equals and compareTo

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

MethodWhat it returnsExample with s = "banana"
length()the number of characters6
substring(from, to)characters from index from up to but not including tos.substring(1, 3) is "an"
substring(from)everything from index from to the ends.substring(4) is "na"
indexOf(str)index of the first match of str, or -1 if there is nones.indexOf("an") is 1
equals(other)true if both have exactly the same characterss.equals("Banana") is false
compareTo(other)negative if s comes first alphabetically, 0 if equal, positive if laters.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.

  1. 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 solution
    1. 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.
    2. Step 2: word.substring(3, 6) takes indexes 3, 4 and 5 (stopping before 6): "put".
    3. Step 3: word.indexOf("t") finds the first t at index 5.
    4. Step 4: part + spot is "put" + 5, which is "put5".
    5. Step 5: word.substring(5) is everything from index 5 on: "ter". Joined with word.length(), 8, that's "ter8".

    Answer: Two lines: put5, then ter8.

  2. 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 solution
    1. Step 1: s is "stone", with s=0, t=1, o=2, n=3, e=4. Its length is 5.
    2. Step 2: s.substring(s.length() - 1) is s.substring(4), the last letter: "e".
    3. Step 3: s.substring(1, s.length() - 1) is s.substring(1, 4), the middle: "ton".
    4. Step 4: s.substring(0, 1) is the first letter: "s".
    5. Step 5: Joined: "e" + "ton" + "s". The original s is unchanged, since strings are immutable.

    Answer: It prints etons.

Common mistakes

  • Thinking substring(a, b) includes index b. 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 ==. Use equals for same characters, or compareTo for alphabetical order.
  • Using length() as a valid index. The last index is length() - 1.

On the exam

  • The Methods and Control Structures free-response question has a part that needs String methods. Practice substring(i, i + 1) for single letters and indexOf returning -1 for "not found".
  • For tracing questions, write the string out with its indexes underneath before you work out any substring call.

Connected topics

Videos

  • AP Computer Science A - Topic 1.15 - Part 1: String Manipulation

    Tim Gallagher Computer ScienceWatch on YouTube (opens in a new tab)

  • AP CSA Unit 1 String Methods (2025)

    PickcodeWatch on YouTube (opens in a new tab)

  • substring And length (Java String Methods)

    Bill BarnumWatch on YouTube (opens in a new tab)

  • AP Computer Science A - Topic 1.15 - Part 2: String Manipulation

    Tim Gallagher Computer ScienceWatch on YouTube (opens in a new tab)

  • AP Computer Science A - Topic 1.15 - Part 3: String Manipulation

    Tim Gallagher Computer ScienceWatch on YouTube (opens in a new tab)

  • Java Strings are Immutable - Here's What That Actually Means

    Coding with JohnWatch on YouTube (opens in a new tab)

Check yourself

4 questions on 1.15 String Manipulation. Pick an answer to see if you got it, and why.

Question 1 of 4

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?

Question 2 of 4

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?

Question 3 of 4

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?

Question 4 of 4

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