Topic 1.15 — String Manipulation
Goal: use common String methods to examine and build new strings (length, substring, index, concatenation),
and trace code that combines these operations.
The big idea
Strings are objects. You don’t “change” a string using methods—instead,
methods usually return a new string (or a value like an int).
This matters for tracing: if you don’t assign the result, the original string stays the same.
Two super-common patterns
Get info (returns numbers/characters)
int n = s.length();
char c = s.charAt(0);
Make a new string (returns a String)
String t = s.substring(1, 4);
String u = s + "!!";
Key String methods (you’ll see these a LOT)
| Method / Operation | What it does | Returns |
|---|---|---|
s.length() |
Number of characters in s |
int |
s.substring(a, b) |
Characters from index a up to (not including) b |
String |
s.substring(a) |
Characters from index a to the end |
String |
s.indexOf(x) |
Index of the first occurrence of x (often a String) |
int |
s.charAt(i) |
Character at index i |
char |
+ (concatenation) |
Joins strings together | String |
You’ll practice these a lot because AP loves asking “what is the output?” or “what value is stored?”
Indexes: remember they start at 0
String s = "APCSA";
// indexes: 01234
s.charAt(0)is'A's.charAt(4)is'A's.length()is5
Substring rule (most-tested detail)
substring(a, b) includes a but does not include b.
String s = "computer";
String sub = s.substring(1, 4); // "omp"
Concatenation tricks
If either side of + is a String, Java turns the other side into a String and concatenates.
String s = "Score: " + 10; // "Score: 10"
String t = "A" + 1 + 2; // "A12"
String u = 1 + 2 + "A"; // "3A"
Common errors (what would break)
charAt(i)with an invalid index (like-1ori >= length)substring(a, b)with invalid bounds (likea > bor out of range)
On the exam, they usually avoid truly “crashy” cases unless the question is about spotting the error.
Exam mindset
- Indexing starts at 0.
substring(a, b)excludesb.- Many String methods return a new String—store the result if you need it.
- Trace concatenation left-to-right.
Quick self-check
- If
s = "hello", what iss.length()? - If
s = "hello", what iss.substring(1, 4)? - What is
"A" + 1 + 2? - What is
1 + 2 + "A"? - Why does
substring“stop before” the end index?