Lesson 1.15: String Manipulation | AP CSA

Unit 1 · Lesson 1.15 · Code Mechanics

Lesson 1.15: String Manipulation

Reading time: 12–15 min·Practice: 8 exercises·Mastery: applied scenario

What you'll learn in this lesson

  • 1.15.A. Create String objects, concatenate Strings and primitives with + and +=, and explain why Strings are immutable.
  • 1.15.B. Call all six String Quick Reference methods and determine their return values: length(), substring(from,to), substring(from), indexOf(str), equals(other), compareTo(other).

This lesson is part of the AP CSA Course and Exam Description (effective May 2027).

AP exam weight: String manipulation is the highest-frequency topic in Unit 1 and appears in both MCQ and FRQ. All six methods below are on the Java String API and the AP Quick Reference. Know each method cold.

String creation and immutability

A String object represents a sequence of characters. String is in java.lang — no import needed. Strings can be created with a literal or the constructor.

Creating Strings

String a = "hello";              // string literal (most common)
String b = new String("hello");  // constructor (less common)

Strings Are Immutable

Once created, a String object’s character sequence cannot change. Every String method that “modifies” a String actually returns a new String object; the original is untouched.

String s = "hello";
s.toUpperCase();           // returns new String "HELLO" -- s unchanged
System.out.println(s);     // prints: hello
s = s.toUpperCase();       // now s points to the new "HELLO" object
System.out.println(s);     // prints: HELLO

String concatenation

The + and += Operators

Two Strings joined with + produce a new String. A primitive concatenated with a String is automatically converted to its String representation.

String name = "Java";
int version = 17;
String result = name + " " + version;  // "Java 17"
result += "!";                          // "Java 17!"

AP Trap: left-to-right evaluation order with + matters

"total: " + 3 + 4"total: 3" then "total: 34" — two concatenations.
"total: " + (3 + 4)"total: " + 7"total: 7" — addition first.
3 + 4 + " total"7 + " total""7 total" — int addition first, then concat.

String indices: 0-based

Characters in a String are indexed starting at 0. The last valid index is length() - 1. Accessing an index outside [0, length()-1] throws StringIndexOutOfBoundsException.

Index diagram for "computer" (length 8)

c o m p u t e r
0 1 2 3 4 5 6 7

The six Quick Reference methods

length()

int length() — returns the number of characters.

"computer".length()   // 8
"".length()           // 0

substring(from, to) and substring(from)

String substring(int from, int to) — returns characters at indices from through to - 1. The to index is exclusive. Length of result = to - from.

String substring(int from) — returns characters from from to the end. Equivalent to substring(from, length()).

"computer".substring(0, 4)  // "comp"  (indices 0,1,2,3)
"computer".substring(4)     // "uter"  (indices 4,5,6,7)
"computer".substring(3, 4)  // "p"     (single char at index 3)

AP Trap: substring exclusive endpoint

To extract the single character at index i: s.substring(i, i + 1).
s.substring(i, i) returns an empty String (from == to).
s.substring(0, s.length()) returns the entire string.

indexOf(str)

int indexOf(String str) — returns the index of the first occurrence of str in the String. Returns -1 if not found.

"computer".indexOf("put")   // 3
"computer".indexOf("xyz")   // -1
"abcabc".indexOf("bc")      // 1  (first occurrence)

equals(other)

boolean equals(Object other) — returns true if the two Strings have the same character sequence, case-sensitive.

"hello".equals("hello")   // true
"hello".equals("Hello")   // false (case matters)
"hello".equals(null)      // false (does not throw NPE)

AP Trap: == vs equals()

== compares references (addresses). Two String objects with identical content can have different addresses — == may return false even when the characters match. Always use .equals() to compare String content.

compareTo(other)

int compareTo(String other) — compares lexicographically (dictionary order).

Returns a value < 0 if this comes before other.
Returns 0 if the strings are equal.
Returns a value > 0 if this comes after other.

"apple".compareTo("banana")   // negative (a before b)
"cat".compareTo("cat")        // 0
"zebra".compareTo("ant")      // positive (z after a)

Uppercase letters come before lowercase in Unicode: "A".compareTo("a") is negative.

toString() and String concatenation with objects

When any object is concatenated with a String using +, Java implicitly calls the object’s toString() method. Every class inherits toString() from Object, though the default implementation returns a class name and hash — not necessarily useful content.

▶ Java Code Editor
Try It Yourself
Write real Java, hit Run, and your code executes on a live compiler. Output is checked automatically.
Tier 2 · AP Practice

Practice Questions

What is the value of result after this code executes?

String s = "examination";
String result = s.substring(4, 8);
Index the string: e(0)x(1)a(2)m(3)i(4)n(5)a(6)t(7)i(8)... Write down chars at indices 4,5,6,7 before choosing.
A. "exami"
B. "inat"
C. "inat" (same as B)
D. "tion"
B. e(0)x(1)a(2)m(3)i(4)n(5)a(6)t(7)i(8)... substring(4,8) includes indices 4,5,6,7 and excludes index 8. Result: "inat". A would be substring(0,5). D would be substring(7,11).
What does the following code print?

System.out.println("score: " + 4 + 6);
Evaluate strictly left-to-right. What type does the first + produce?
A. score: 10
B. score: 10.0
C. score: 4 + 6
D. score: 46
D. Left-to-right: "score: " + 4 = "score: 4" (String concat). Then "score: 4" + 6 = "score: 46" (another String concat). Once a String operand appears, subsequent + operators concatenate rather than add. To get "score: 10" use: "score: " + (4 + 6).
What does "algorithm".indexOf("ith") return?
Map out "algorithm": a(0)l(1)g(2)o(3)r(4)i(5)t(6)h(7)m(8). Where does "ith" start?
A. 5
B. 4
C. -1
D. 6
A. a(0)l(1)g(2)o(3)r(4)i(5)t(6)h(7)m(8). "ith" = i(5)t(6)h(7). Starts at index 5. indexOf returns the index of the first character of the match.
Which expression extracts the single character at index 3 from String s as a String?
A. s.substring(3)
B. s.substring(3, 3)
C. s.substring(3, 4)
D. s.length() - 3
C. substring(3, 4) returns the one character at index 3 (from inclusive, to exclusive). A returns from index 3 to end. B returns empty String (from == to). D returns an int, not a character.
Which of the following correctly compares two Strings for equal content?

I. s1 == s2
II. s1.equals(s2)
III. s1.compareTo(s2) == 0
A. I only
B. II and III only
C. I, II, and III
D. II only
B. I: == compares references, not content — unreliable for String equality. II: equals() compares character sequences — correct. III: compareTo returns 0 when strings are equal — also reliable. II and III work; I does not.
A student writes the following code.

String s = "hello";
s.toUpperCase();
System.out.println(s);

What is printed?
Remember: Strings are immutable. What does toUpperCase() actually do to the original String?
A. HELLO
B. A compile error because toUpperCase() is not a valid String method.
C. An empty String.
D. hello
D. Strings are immutable. toUpperCase() returns a new String "HELLO" but s is never reassigned, so s still references "hello". The return value is discarded. Fix: s = s.toUpperCase();
What does "banana".compareTo("cherry") return?
A. A negative value, because "banana" comes before "cherry" alphabetically.
B. 0, because both strings have 6 characters.
C. A positive value, because 'b' has a higher Unicode value than 'c'.
D. 1, because "banana" is one letter earlier than "cherry".
A. compareTo compares lexicographically. 'b' (98) comes before 'c' (99) in Unicode, so "banana" < "cherry". compareTo returns a negative value. B is wrong: length doesn't determine compareTo. C is wrong: 'b' (98) is less than 'c' (99). D is wrong: the return value is not necessarily 1.
Consider String s = "abcdefg";. Which of the following statements are TRUE?

I. s.substring(s.indexOf("cd")) returns "cdefg".
II. s.indexOf("xyz") returns 0.
III. s.substring(0, s.length()) returns the entire string "abcdefg".
A. I only
B. II and III only
C. I and III only
D. I, II, and III
C. I: indexOf("cd") = 2. substring(2) = "cdefg". True. II: indexOf("xyz") = -1, not 0 (not found returns -1). False. III: substring(0, length()) = substring(0, 7) = entire string "abcdefg". True. I and III are true.
PRACTICE WITH A GAME — CHOOSE ONE:

Output Predictor — String Methods

Predict the exact output. Remember: substring(from,to) excludes the "to" index. indexOf returns -1 if not found.

Question 1 of 6Score: 0

Bug Hunt — String Methods

Each snippet has exactly one buggy line. Click it, then submit.

Bug 1 of 7Caught: 0

Tier 3 · AP Mastery Challenge

The Username Generator

A school system generates usernames from student names. Study the code below.

String first = "Alexandra";
String last = "Chen";
String username = last.toLowerCase() + first.substring(0, 2).toLowerCase();
int discriminator = username.indexOf("a");
System.out.println(username);
System.out.println(discriminator);

Part A: Trace the output

What are the two lines of output?
Trace username step by step: last.toLowerCase(), then first.substring(0,2).toLowerCase(), then concatenate. Then find indexOf("a") on the result.
A. ChenAl
-1
B. chenal
3
C. chenal
2
D. chenal
4
D. last.toLowerCase() = "chen". first.substring(0,2) = "Al", .toLowerCase() = "al". username = "chenal". Indexing "chenal": c(0)h(1)e(2)n(3)a(4)l(5). indexOf("a") returns 4. The correct output is "chenal" on line 1 and 4 on line 2.

Part B: Fix the output

The school wants the username to use only the first letter of the first name (not two). Which change to the username line produces "chenа" (5 chars)?
A. Change substring(0, 2) to substring(0, 0)
B. Change substring(0, 2) to substring(0, 1)
C. Change substring(0, 2) to substring(1, 2)
D. Change substring(0, 2) to substring(2)
B. substring(0, 1) returns only the first character "A", which lowercases to "a". username = "chen" + "a" = "chena" (5 chars). A gives empty string (from==to=0). C gives the second character "l". D gives everything from index 2 onward: "exandra".

Part C: Structured response

A student claims that after the line String username = last.toLowerCase() + first.substring(0, 2).toLowerCase(); executes, the variable last now holds "chen". Is the student correct? Explain why or why not in three to four sentences, referencing the immutability of Strings.

Extension · Beyond the Exam

StringBuilder for frequent modification

Because String concatenation in a loop creates a new object every iteration, Java provides StringBuilder for efficient string building. StringBuilder sb = new StringBuilder(); sb.append("hello"); sb.append(" world"); String result = sb.toString(); performs all modifications on one mutable object and converts to an immutable String at the end. StringBuilder is not on the AP Quick Reference but is essential in professional Java code.

Get in Touch

Whether you're a student, parent, or teacher — I'd love to hear from you.

Just want free AP CS resources?

Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.

Typically responds within 24 hours

Message Sent!

Thanks for reaching out. I'll get back to you within 24 hours.

🏫 Welcome, fellow educator!

I offer curriculum resources, practice materials, and study guides designed for AP CS teachers. Let me know what you're looking for — whether it's classroom materials, a guest speaker, or Teachers Pay Teachers resources.

Email

[email protected]

📚

Courses

AP CSA, CSP, & Cybersecurity

Response Time

Within 24 hours

Prefer email? Reach me directly at [email protected]