Lesson 1.15: String Manipulation | AP CSA
Lesson 1.15: String Manipulation
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.
Practice Questions
result after this code executes?String s = "examination"; String result = s.substring(4, 8);
System.out.println("score: " + 4 + 6);
"algorithm".indexOf("ith") return?s as a String?s.substring(3)
s.substring(3, 3)
s.substring(3, 4)
s.length() - 3
I.
s1 == s2II.
s1.equals(s2)III.
s1.compareTo(s2) == 0
String s = "hello"; s.toUpperCase(); System.out.println(s);
What is printed?
s is never reassigned, so s still references "hello". The return value is discarded. Fix: s = s.toUpperCase();
"banana".compareTo("cherry") return?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".Output Predictor — String Methods
Predict the exact output. Remember: substring(from,to) excludes the "to" index. indexOf returns -1 if not found.
Bug Hunt — String Methods
Each snippet has exactly one buggy line. Click it, then submit.
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
-1
3
2
4
Part B: Fix the output
"chenа" (5 chars)?substring(0, 2) to substring(0, 0)
substring(0, 2) to substring(0, 1)
substring(0, 2) to substring(1, 2)
substring(0, 2) to substring(2)
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.
Scoring Rubric (4 points)
- +1: States the student is incorrect.
- +1: Explains immutability: String objects cannot be changed once created. last.toLowerCase() does not modify the "Chen" object.
- +1: Explains what actually happened: toLowerCase() returned a new String "chen", which was concatenated into username. The variable last still references the original "Chen" object.
- +1: States the fix: to make last hold "chen", you would write last = last.toLowerCase(); to reassign the variable to the new object.
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.
Message Sent!
Thanks for reaching out. I'll get back to you within 24 hours.
Prefer email? Reach me directly at [email protected]