Strings & Objects - Complete Interactive Lesson
Part 1: Core Concepts
🔤 Strings & Objects
Part 1 of 7 — String Methods, Immutability, and Object Basics
String Methods (AP Subset)
| Method | Return Type | Description | Example |
|---|---|---|---|
length() | int | Number of characters | "hello".length() → 5 |
substring(start) | String | From start to end | "hello".substring(2) → "llo" |
substring(start, end) | String | From start to end-1 | "hello".substring(1,4) → "ell" |
indexOf(str) | int | First occurrence (-1 if not found) | "hello".indexOf("ll") → 2 |
equals(str) | boolean | Content comparison | "hi".equals("hi") → true |
compareTo(str) | int | Lexicographic: neg, 0, or pos | "apple".compareTo("banana") → negative |
🔑 Strings are immutable — once created, their content cannot be changed. Methods like
substring()return a NEW String; the original is unchanged.
String Indexing
Index: 0 1 2 3 4
String: "h e l l o"
- First character is at index 0 (zero-based)
- Last character is at index length() - 1
substring(a, b)includes indexabut EXCLUDES indexb
Concept Check 🎯
String Immutability
String s = "hello";
s.substring(1); // Returns "ello" but s is still "hello"!
s = s.substring(1); // Now s = "ello" (reassigned to the new String)
compareTo() Details
| Return Value | Meaning |
|---|---|
| Negative | Calling string comes before parameter alphabetically |
| 0 | Strings are equal |
| Positive | Calling string comes after parameter alphabetically |
"apple".compareTo("banana") // Negative (a < b)
"cat".compareTo("cat") // 0 (equal)
"dog".compareTo("cat") // Positive (d > c)
Escape Sequences
| Sequence | Meaning |
|---|---|
\\ | Backslash |
\" | Double quote inside a String |
\n | Newline |
These three are the only escape sequences in the AP Java subset.
Applied Recall ✍️
-
String indexing in Java starts at _______ (not 1).
-
Strings in Java are _______, meaning their content cannot be changed after creation.
-
The method _______ is used to compare the content of two String objects (not ==).
Evaluate the Call 🔍
AP Exam Strategy: Strings
- substring(a, b) includes index a but EXCLUDES index b — practice counting characters
- indexOf() returns -1 if not found — check for this in conditional code
- Remember: Strings are immutable! Always capture the return value:
s = s.substring(1); - == for Strings is WRONG — always use
.equals()on the AP exam - compareTo returns negative/zero/positive — you do not need to know the exact number
- Practice tracing String manipulations character by character using index numbers
AP-Style Application 🎯
Part 2: String Objects, Concatenation, and equals vs ==
🔤 Strings & Objects
Part 2 of 7 — String Objects, Concatenation, and equals vs ==
Part 1 showed what the String methods return. This part looks at what a String variable actually holds, what happens when + mixes Strings with numbers, and why two Strings with the same letters can still fail an == test.
Topics in This Part
| Section |
|---|
| Creating String objects: literals, the constructor, "" and null |
| Concatenation with numbers, booleans, and objects |
| += builds a new String |
| equals vs == |
| null Strings and NullPointerException |
🔑 Key Concept: A String variable stores a reference to a String object, not the characters themselves. Most String surprises on the AP exam come from forgetting that.
Creating String Objects
String is a class in the java.lang package, so it is available in every program without an import. AP code makes String objects in two ways: a string literal in double quotes, or the String(String str) constructor from the Java Quick Reference.
String city = "Boston"; // a string literal
String copy = new String("Boston"); // the constructor String(String str)
String blank = ""; // the empty String: an object with length() 0
String none = null; // no String object at all
Each variable is a reference variable. A reference diagram shows what is stored:
city --> "Boston"
copy --> "Boston" (a second, separate object with the same characters)
blank --> ""
none null (refers to nothing)
"" is not the same as null
"" (empty String) | null | |
|---|---|---|
| Is there an object? | Yes | No |
length() | returns 0 | throws NullPointerException |
In concatenation, "Hi " + s | gives "Hi " | gives "Hi null" |
| Typical use | starting value for a String you will build with += | "no value yet" |
💡 When you build a String in a loop, start from
"", never fromnull. Starting from null puts the four letters "null" at the front of your result.
Concatenation with Other Types
Three rules decide what + does:
- If either operand is a String, + means concatenation. The other operand is converted to its String form first.
- Operators of the same precedence are evaluated left to right, so whether a + adds or concatenates depends on what has been built so far.
*,/and%happen before +, and parentheses force anything inside them to happen first.
| Expression | Steps | Result |
|---|---|---|
"Total: " + 3 + 4 | "Total: 3" + 4 | "Total: 34" |
3 + 4 + " total" | 7 + " total" | "7 total" |
"Total: " + (3 + 4) | parentheses first | "Total: 7" |
"Avg " + 7 / 2 | int division first: 3 | "Avg 3" |
"Avg " + 7.0 / 2 | double division first: 3.5 | "Avg 3.5" |
"x" + 2.0 | a double always shows a decimal point | "x2.0" |
"ok? " + (5 > 3) | boolean becomes "true" | "ok? true" |
Two more facts:
"Total: " + 3 - 4does not compile. The left part becomes the String "Total: 3", and you cannot subtract an int from a String.- When an object is concatenated, Java calls its
toString()method for you. For a String that is just its own text. Writing your own toString for a class is not on the AP exam.
Worked Example: Reading a Mixed Expression
int a = 2;
int b = 5;
System.out.println(a + b + " and " + a + b);
| Step | Operation | Value so far |
|---|---|---|
| 1 | a + b (both int) | 7 |
| 2 | 7 + " and " | "7 and " |
| 3 | "7 and " + a | "7 and 2" |
| 4 | "7 and 2" + b | "7 and 25" |
Output: 7 and 25. The first + adds because nothing is a String yet; every + after the first String concatenates.
Trace the Output 🎯
Segment A
int a = 5;
int b = 2;
System.out.println(a + b + "=" + a + b);
Segment B
double price = 4.0;
int qty = 3;
String msg = "Cost: " + price * qty;
System.out.println(msg);
+= Builds a New String
Because Strings are immutable, += cannot add letters to an existing object. It builds a new String and moves the variable to it.
String word = "cat";
String other = word; // both variables refer to the same "cat" object
word += "s"; // same as word = word + "s";
System.out.println(word); // cats
System.out.println(other); // cat
Before word += "s": After word += "s":
word --> "cat" word --> "cats" (new object)
other --> "cat" (same) other --> "cat" (unchanged)
other still prints cat. Nothing changed the original object; only word was pointed somewhere new. This is exactly how a loop like result += piece; builds an answer: each pass makes a slightly longer String and reassigns result.
equals vs ==
| Test | Question it asks | Use it for Strings? |
|---|---|---|
a == b | Do a and b refer to the same object? | No, it compares references |
a.equals(b) | Do the two Strings hold the same characters in the same order? | Yes, always |
String a = new String("java");
String b = new String("java");
String c = a;
System.out.println(a == b); // false: two different objects
System.out.println(a.equals(b)); // true: same characters
System.out.println(a == c); // true: c refers to the same object as a
System.out.println(a.equals("Java")); // false: equals is case-sensitive
Why == "sometimes works"
Java may let identical string literals share one object, so "java" == "java" can print true. That is a storage detail, not a promise. Strings produced while the program runs, by substring, concatenation, or the constructor, are usually new objects, so == on them is false even when the letters match. The rule never changes: compare String contents with equals.
🎯 AP Connection: Free-response rubrics penalize using == to compare String contents. Multiple-choice questions use it as a distractor in "which expression is true" items.
null Strings and NullPointerException
A variable that holds null has no object behind it. Concatenation handles that case; method calls do not.
String s = null;
String t = "";
System.out.println(t.length()); // 0
System.out.println("x" + s); // xnull
System.out.println("abc".equals(s)); // false
System.out.println(s.length()); // throws NullPointerException
| Line | Why |
|---|---|
t.length() | t refers to a real object with no characters |
"x" + s | concatenation turns a null reference into the text "null" |
"abc".equals(s) | the method runs on "abc"; equals returns false for a null argument |
s.length() | there is no object to run length() on, so the program stops with a run-time error |
💡
"yes".equals(answer)safely returns false whenansweris null, whileanswer.equals("yes")throws. Calling the method on the String you know exists is a common defensive habit.
References and null 🎯
Segment C
String a = new String("hi");
String b = new String("hi");
String alias = b;
Segment D
String name = null;
Applied Recall ✍️
-
What is printed by
System.out.println(1 + 2 + "A" + 1 + 2);? -
After these statements run, what is
s.length()?
String s = "ab";
s += s;
s += "c";
- To check whether two Strings contain the same characters, call the _______ method.
Part 2 Summary
| Idea | Remember |
|---|---|
| String variables | hold a reference to an object (or null) |
"" vs null | empty String is an object; null is no object |
| Concatenation | left to right; once a String appears, + joins text |
| Precedence | *, /, % and parentheses happen before + |
+= on a String | builds a new object and reassigns the variable |
| Comparing contents | equals, never == |
| Method call on null | NullPointerException at run time |
Next: Part 3 puts substring and indexOf to work, pulling names, codes, and words out of larger Strings without going out of bounds.
Part 3: Extracting Pieces with substring and indexOf
🔤 Strings & Objects
Part 3 of 7 — Extracting Pieces with substring and indexOf
Most String questions on the AP exam boil down to one job: find a position with indexOf, then cut out a piece with substring. This part turns that job into recipes you can use without recounting every time.
Topics in This Part
| Section |
|---|
| Substring recipes: first, last, and one-character pieces |
| Worked examples: splitting at a delimiter, email parts, replacing a word |
| Guarding against indexOf returning -1 |
| The bounds rule and StringIndexOutOfBoundsException |
🔑 Key Concept:
substring(a, b)returns the characters at indicesathroughb - 1, so the piece always has exactly b - a characters.
Substring Recipes
Write the indices under the String before you do anything else:
Index: 0 1 2 3 4 5
s: p l a n e t s.length() is 6
| Goal | Expression | Result for "planet" |
|---|---|---|
| First character | s.substring(0, 1) | "p" |
| Last character | s.substring(s.length() - 1) | "t" |
| Character at index i (here i = 2) | s.substring(i, i + 1) | "a" |
| First n characters (n = 3) | s.substring(0, n) | "pla" |
| Last n characters (n = 3) | s.substring(s.length() - n) | "net" |
| Everything after the first character | s.substring(1) | "lanet" |
| Everything except the last character | s.substring(0, s.length() - 1) | "plane" |
The length rule
s.substring(a, b) has b - a characters. "planet".substring(1, 4) has 4 - 1 = 3 characters: "lan". Use the rule to check your answer: if you counted 4 letters for substring(1, 4), you included the end index by mistake.
💡 A one-character piece such as
s.substring(i, i + 1)is still a String, so test it with equals:s.substring(0, 1).equals("p").
Recipe Check 🎯
String w = "keyboard";
Worked Examples: Find, Then Cut
Example 1 — Split "Last, First"
String full = "Lovelace, Ada";
int comma = full.indexOf(","); // 8
String last = full.substring(0, comma); // "Lovelace"
String first = full.substring(comma + 2); // "Ada"
System.out.println(first + " " + last); // Ada Lovelace
Index: 0 1 2 3 4 5 6 7 8 9 10 11 12
full: L o v e l a c e , A d a
substring(0, comma)stops before the comma, so the comma is not included.comma + 2skips both the comma (index 8) and the space (index 9). Usingcomma + 1would give" Ada"with a leading space.
Example 2 — The parts of an email address
String email = "grace@navy.mil";
int at = email.indexOf("@"); // 5
String user = email.substring(0, at); // "grace"
String domain = email.substring(at + 1); // "navy.mil"
int dot = domain.indexOf("."); // 4 (an index inside domain)
String ending = domain.substring(dot + 1); // "mil"
Notice that dot is an index in domain, not in email. Each indexOf result only makes sense for the String it was called on.
Example 3 — Replace the first occurrence of a word
String s = "the cat sat";
String t = "cat";
int p = s.indexOf(t); // 4
s = s.substring(0, p) + "dog" + s.substring(p + t.length()); // "the dog sat"
The pattern is before + new + after. s.substring(0, p) is "the ", and s.substring(p + t.length()) starts right after the old word: index 4 + 3 = 7, giving " sat". Writing t.length() instead of the number 3 keeps the code correct for any word.
Guarding Against -1
indexOf never throws an exception. When the target is missing it returns -1, and that -1 causes trouble one line later:
String code = "AB1234"; // no dash this time
int dash = code.indexOf("-"); // -1
String prefix = code.substring(0, dash); // substring(0, -1): exception!
The fix is to check the result before cutting (selection statements are covered in Unit 2, and this guard is one of their most common uses):
String prefix = code; // default: keep the whole code
int dash = code.indexOf("-");
if (dash >= 0) {
prefix = code.substring(0, dash);
}
code | dash | prefix |
|---|---|---|
"AB-1234" | 2 | "AB" |
"AB1234" | -1 | "AB1234" |
"-99" | 0 | "" |
The last row is legal: substring(0, 0) is the empty String.
The Bounds Rule
s.substring(a, b) runs only when 0 <= a <= b <= s.length(). s.substring(a) runs only when 0 <= a <= s.length(). Anything else compiles but throws a StringIndexOutOfBoundsException when the line executes.
For s = "java" (length 4):
| Call | Result | Reason |
|---|---|---|
s.substring(4) | "" | start may equal the length; nothing is left |
s.substring(2, 2) | "" | equal start and end give the empty String |
s.substring(0, 4) | "java" | end may equal the length |
s.substring(0, 5) | exception | end is past the length |
s.substring(3, 2) | exception | start is after end |
s.substring(-1) | exception | negative start |
s.substring(s.indexOf("x")) | exception | indexOf gave -1 |
🎯 AP Connection: The length itself is a legal end index but never a legal single-character index.
s.substring(s.length())is"", whiles.substring(s.length(), s.length() + 1)throws. Watch for that difference in loop bounds in Part 5.
Applied Recall ✍️
String s = "stadium";
-
What does
s.indexOf("dium")return? -
What is
s.substring(s.indexOf("a") + 1).length()? -
What is the largest int
kfor whichs.substring(k)runs without an exception?
Find and Cut 🎯
Segment A
String s = "sunflower";
int p = s.indexOf("flow");
System.out.println(s.substring(0, p) + s.substring(p + 4));
Segment B
String t = "data";
int q = t.indexOf("z");
System.out.println(t.substring(q + 1));
Part 3 Summary
| Task | Pattern |
|---|---|
| Character at i | s.substring(i, i + 1) |
| Last character | s.substring(s.length() - 1) |
| Text before a marker | s.substring(0, s.indexOf(marker)) |
| Text after a one-character marker | s.substring(s.indexOf(marker) + 1) |
| Replace first occurrence | before + new + after using p + t.length() |
| Missing marker | indexOf gives -1; check >= 0 before cutting |
| Legal call | 0 <= a <= b <= s.length() |
Next: Part 4 compares whole Strings with compareTo and explains why Java puts "Zebra" before "apple".
Part 4: Ordering Strings with compareTo
🔤 Strings & Objects
Part 4 of 7 — Ordering Strings with compareTo
Part 1 gave the sign table for compareTo: negative, zero, or positive. This part shows how Java decides which String comes first, why its order is not quite dictionary order, and how to turn compareTo into the boolean conditions that exam code uses.
Topics in This Part
| Section |
|---|
| The lexicographic algorithm, step by step |
| Unicode order: space, digits, uppercase, lowercase |
| Writing conditions with compareTo |
| compareTo vs equals, and common traps |
🔑 Key Concept:
a.compareTo(b)behaves like "a minus b". If the result is negative,acomes first; if it is positive,bcomes first; if it is 0, the Strings are identical.
How compareTo Decides
To evaluate a.compareTo(b), Java walks both Strings from index 0:
- Compare the characters at the same index.
- At the first index where they differ, the String whose character has the smaller Unicode value comes first. The result is negative if that String is
a, positive if it isb. - If one String runs out while every character so far has matched, the shorter String comes first (it is a prefix of the other).
- If both run out at the same time, the Strings are equal and the result is 0.
Worked Table
| Call | Deciding step | Sign | Meaning |
|---|---|---|---|
"cart".compareTo("care") | index 3: "t" vs "e" | positive | "cart" comes after "care" |
"bat".compareTo("bath") | "bat" runs out first | negative | a prefix comes first |
"Zebra".compareTo("apple") | index 0: "Z" vs "a" | negative | uppercase comes before lowercase |
"apple".compareTo("Apple") | index 0: "a" vs "A" | positive | lowercase comes after uppercase |
"10".compareTo("9") | index 0: "1" vs "9" | negative | text order, not numeric order |
"dog".compareTo("dog") | no difference, same length | 0 | equal |
Only the first difference matters. In "cart" vs "care", nothing after index 3 is ever looked at, and the lengths do not matter because a difference was found before either String ran out.
Unicode Order Is Not Dictionary Order
Every character has a Unicode number. The groups you need to know come in this order:
| Group | Unicode values | Example |
|---|---|---|
| space | 32 | " " |
| digits | 48 to 57 | "0" through "9" |
| uppercase letters | 65 to 90 | "A" through "Z" |
| lowercase letters | 97 to 122 | "a" through "z" |
Consequences that show up in exam questions:
- Every uppercase letter comes before every lowercase letter, so
"Zoo"comes before"ant". - Numbers stored as text compare digit by digit.
"100"comes before"25"because "1" comes before "2". Text order and numeric order disagree here. - A space beats any letter or digit, so
"New York"comes before"Newark"(index 3: space vs "a").
💡 The AP exam does not require memorizing the Unicode numbers. Remember the order: space, digits, uppercase, lowercase.
Only the sign counts
Java's compareTo returns a specific int (for example, the difference between the two deciding characters), but the AP exam only relies on whether it is negative, zero, or positive. Never write code such as a.compareTo(b) == -1; it can fail even when a comes first.
Which Comes First? 🎯
Writing Conditions with compareTo
Read a.compareTo(b) as "a minus b" and the condition almost writes itself:
| You want to test | Write |
|---|---|
a comes before b | a.compareTo(b) < 0 |
a comes after b | a.compareTo(b) > 0 |
a and b are the same text | a.compareTo(b) == 0 or a.equals(b) |
a comes before b or matches it | a.compareTo(b) <= 0 |
Swapping the two Strings flips the sign: if a.compareTo(b) is negative, then b.compareTo(a) is positive.
Worked Example 1 — Are three words in order?
String w1 = "ant";
String w2 = "Bee";
String w3 = "cat";
boolean ordered = w1.compareTo(w2) <= 0 && w2.compareTo(w3) <= 0;
System.out.println(ordered);
| Step | Comparison | Sign | Clause |
|---|---|---|---|
| 1 | "ant".compareTo("Bee"): "a" vs "B" | positive | false |
| 2 | short-circuit: && stops | — | — |
Output: false. A dictionary lists ant, Bee, cat in order, but Java puts uppercase "B" before lowercase "a", so "Bee" comes before "ant".
Worked Example 2 — Keep the earlier name
String a = "Ramirez";
String b = "Ramos";
String first = a;
if (b.compareTo(a) < 0) {
first = b;
}
System.out.println(first);
The Strings match through "Ram". At index 3, "o" (from "Ramos") vs "i" (from "Ramirez"): "o" comes later, so b.compareTo(a) is positive and first stays "Ramirez". Output: Ramirez. Length played no part, because a difference appeared at index 3.
Sign of the Result 🔍
Choose the sign of each call.
compareTo vs equals, and Common Traps
| Point | Detail |
|---|---|
| Return types | compareTo returns an int; equals returns a boolean. if (a.compareTo(b)) does not compile. |
| Agreement | For Strings, a.compareTo(b) == 0 is true exactly when a.equals(b) is true. |
| Case | Both are case-sensitive: "Cat".equals("cat") is false and their compareTo is not 0. |
| Exact values | Test only the sign: < 0, > 0, == 0. |
| null argument | a.compareTo(null) throws a NullPointerException. |
🎯 AP Connection: compareTo is how String data gets sorted and searched later in the course, when you work with arrays and lists of Strings. Those algorithms use the same three conditions from the table above.
Conditions with compareTo 🎯
String s1 = "Kite";
String s2 = "kit";
String s3 = "kite";
Part 4 Summary
| Rule | Example |
|---|---|
| First difference decides | "cart" after "care" |
| Prefix comes first | "bat" before "bath" |
| Space, digits, uppercase, lowercase | "Zoo" before "ant"; "100" before "25" |
| "a before b" | a.compareTo(b) < 0 |
| Equal text | a.compareTo(b) == 0, same as a.equals(b) |
| Sign only | never test for == -1 or == 1 |
Next: Part 5 puts these tools inside loops to count, filter, reverse, and search Strings one piece at a time.
Part 5: String Traversal Algorithms
🔤 Strings & Objects
Part 5 of 7 — String Traversal Algorithms
A String traversal visits a String one piece at a time with a loop. The AP course names a short list of standard String algorithms, and every one of them is a variation on the same loop.
Topics in This Part
| Section |
|---|
| The one-character traversal loop |
| Counting: letters with a property, and occurrences of a substring |
| Building new Strings: filtering and reversing |
| Finding and removing every occurrence |
| Off-by-one errors and how to spot them |
🔑 Key Concept: Every traversal answers three questions: where does the loop start, where does it stop, and what piece does each pass examine? Get those right and the rest is bookkeeping.
The Traversal Loop
for (int i = 0; i < s.length(); i++) {
String letter = s.substring(i, i + 1);
// examine letter
}
iruns from 0 tos.length() - 1, the last legal single-character index.s.substring(i, i + 1)is the one-character String at indexi. On the last pass,i + 1equalss.length(), which is a legal end index.- Each
letteris a String, so test it withequalsorindexOf, never==.
Algorithm 1 — Count letters with a property
public static int countVowels(String s) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
String letter = s.substring(i, i + 1);
if ("aeiou".indexOf(letter) >= 0) {
count++;
}
}
return count;
}
The test "aeiou".indexOf(letter) >= 0 asks whether the one-letter String appears inside "aeiou". For letter = "u" it returns 4 (found); for letter = "d" it returns -1 (not found).
| Call | Vowels found | Returns |
|---|---|---|
countVowels("education") | e, u, a, i, o | 5 |
countVowels("rhythm") | none | 0 |
countVowels("ECHO") | none: "E" and "O" are not in "aeiou" | 0 |
To count uppercase vowels too, search in "aeiouAEIOU" instead.
Algorithm 2 — Count occurrences of a substring
To look at pieces longer than one character, slide a window of target.length() characters across the String:
public static int countOccurrences(String s, String target) {
int count = 0;
int len = target.length();
for (int i = 0; i <= s.length() - len; i++) {
if (s.substring(i, i + len).equals(target)) {
count++;
}
}
return count;
}
The last window starts at index s.length() - len, so the condition is i <= s.length() - len. Windows may overlap:
| Call | Windows that match | Returns |
|---|---|---|
countOccurrences("banana", "ana") | start at 1 and 3 | 2 |
countOccurrences("aaaa", "aa") | start at 0, 1, and 2 | 3 |
countOccurrences("hi", "hello") | loop never runs (2 - 5 is negative) | 0 |
Counting Traces 🎯
Segment A
String s = "mississippi";
int count = 0;
for (int i = 0; i < s.length() - 1; i++) {
if (s.substring(i, i + 2).equals("ss")) {
count++;
}
}
System.out.println(count);
Building New Strings
Strings are immutable, so "changing" a String really means building a new one in a variable that starts as "" and grows with each pass.
Algorithm 3 — Remove every copy of a letter (filter)
public static String removeLetter(String s, String letter) {
String result = "";
for (int i = 0; i < s.length(); i++) {
String current = s.substring(i, i + 1);
if (!current.equals(letter)) {
result += current;
}
}
return result;
}
removeLetter("bookkeeper", "e") returns "bookkpr": every letter except the three e's is appended.
Algorithm 4 — Reverse by prepending
Part 1 reversed a String by walking backward and appending. You can also walk forward and put each letter in front:
String s = "stop";
String reversed = "";
for (int i = 0; i < s.length(); i++) {
reversed = s.substring(i, i + 1) + reversed;
}
i | letter | reversed after the pass |
|---|---|---|
| 0 | "s" | "s" |
| 1 | "t" | "ts" |
| 2 | "o" | "ots" |
| 3 | "p" | "pots" |
Writing reversed = reversed + letter instead would rebuild "stop" unchanged. A palindrome check is then one line: boolean isPal = s.equals(reversed);
Finding and Removing Every Occurrence
Algorithm 5 — Report every position of a target
String s = "abcabcab";
String t = "ab";
for (int i = 0; i <= s.length() - t.length(); i++) {
if (s.substring(i, i + t.length()).equals(t)) {
System.out.print(i + " ");
}
}
Output: 0 3 6. This is the counting window from Algorithm 2 with a print in place of count++.
Algorithm 6 — Remove every copy of a word with indexOf
indexOf only finds the first occurrence, so call it again after each removal until it returns -1:
String s = "la-la-land";
String t = "la";
int p = s.indexOf(t);
while (p >= 0) {
s = s.substring(0, p) + s.substring(p + t.length());
p = s.indexOf(t);
}
System.out.println(s);
| Pass | p | s after the removal |
|---|---|---|
| 1 | 0 | "-la-land" |
| 2 | 1 | "--land" |
| 3 | 2 | "--nd" |
| stop | -1 | — |
Output: --nd. One subtlety: a removal can create a new match. Starting from "aabb" and removing "ab" leaves "ab", which the next pass removes, so the loop ends with the empty String.
Off-by-One Errors
| Bug | What happens |
|---|---|
i <= s.length() with substring(i, i + 1) | the last pass calls substring(s.length(), s.length() + 1): StringIndexOutOfBoundsException |
int i = 1 as the start | index 0 is never examined |
i < s.length() - len in a window loop | the last window is skipped |
i < s.length() with substring(i, i + len) and len of 2 or more | throws once i + len passes the length |
reversed = reversed + letter | copies the String instead of reversing it |
letter == "a" | compares references, so matches can be missed |
🎯 AP Connection: When an exam question asks "which loop header avoids an exception," check the largest value of
ithe loop allows and plug it into every substring call. The end index may equals.length()but never exceed it.
Building and Bounds 🎯
Segment B
String s = "lemon";
String result = "";
for (int i = 1; i < s.length(); i += 2) {
result = s.substring(i, i + 1) + result;
}
System.out.println(result);
Segment C
String s = "code";
String out = "";
for (int i = 0; i <= s.length(); i++) {
out += s.substring(i, i + 1);
}
System.out.println(out);
Applied Recall ✍️
-
What does
countVowels("audio")return? -
How many times does the loop body in
countOccurrencesrun forcountOccurrences("abcdefgh", "abc")? -
Type the word the prepend loop from Algorithm 4 produces when
sis"flow"(no quotation marks).
Part 5 Summary
| Algorithm | Loop bound | Key line |
|---|---|---|
| Examine each letter | i < s.length() | String letter = s.substring(i, i + 1); |
| Count a property | i < s.length() | if ("aeiou".indexOf(letter) >= 0) count++; |
| Count or find a substring | i <= s.length() - len | s.substring(i, i + len).equals(target) |
| Filter | i < s.length() | if (!current.equals(letter)) result += current; |
| Reverse | i < s.length() | reversed = letter + reversed; |
| Remove every copy | while (p >= 0) | s = s.substring(0, p) + s.substring(p + t.length()); |
Next: Part 6 is AP-style practice, including two free-response style methods built from these patterns.
Part 6: AP-Style Practice
🔤 Strings & Objects
Part 6 of 7 — AP-Style Practice
Strings appear all over the AP Computer Science A exam. Multiple-choice questions ask you to trace substring, indexOf, and compareTo calls, often inside a loop. Free-response question 1 (Methods and Control Structures) regularly asks you to write a method that walks through a String. This part practices both.
How to Attack a String Question
| Step | Do this |
|---|---|
| 1 | Write the indices under every String in the code. |
| 2 | For each substring call, write the start and end and check 0 <= a <= b <= length. |
| 3 | For loops, make a trace table: i, the piece examined, and the accumulator. |
| 4 | For each comparison, ask whether it compares contents (equals, compareTo) or references (==). |
| 5 | Find where the output happens: inside the loop, after it, or never (if an exception is thrown first). |
🔑 Key Concept: Most wrong answers on String traces are the result of one predictable slip: an end index counted as included, a loop that runs one pass too many or too few, or a prepend read as an append.
Practice Set 1: Tracing 🎯
Segment A
String s = "abcdef";
String r = "";
for (int i = 0; i < s.length(); i += 2) {
r += s.substring(i + 1, i + 2) + s.substring(i, i + 1);
}
System.out.println(r);
Segment B
String w = "ALGORITHM";
int p = w.indexOf("RI");
String x = w.substring(p) + w.substring(0, p);
System.out.println(x.length() + " " + x.substring(0, 3));
FRQ-Style Task 1 — countDoubles
Prompt. Write a static method countDoubles that returns the number of indices i where the character at i is the same as the character at i + 1.
| Call | Matching pairs | Returns |
|---|---|---|
countDoubles("bookkeeper") | oo, kk, ee | 3 |
countDoubles("aaabb") | aa (0 and 1), aa (1 and 2), bb | 3 |
countDoubles("x") | none | 0 |
countDoubles("") | none | 0 |
Plan before you write
- Each pass looks at two neighbors, so the last legal
iisstr.length() - 2. The loop condition isi < str.length() - 1. - Pull out the neighbors with
substring(i, i + 1)andsubstring(i + 1, i + 2). - Compare them with equals and count.
Solution
public static int countDoubles(String str) {
int count = 0;
for (int i = 0; i < str.length() - 1; i++) {
String a = str.substring(i, i + 1);
String b = str.substring(i + 1, i + 2);
if (a.equals(b)) {
count++;
}
}
return count;
}
For "" the condition is 0 < -1, which is false, so the loop never runs and the method returns 0 without an exception.
What a rubric looks for
| Point | Earned by |
|---|---|
| Traversal | visits every adjacent pair with no out-of-bounds call |
| Extraction | gets the two neighbors as one-character Strings |
| Comparison | compares contents with equals (not ==) |
| Result | initializes the count, increments it, and returns it after the loop |
Practice Set 2: Reasoning About countDoubles 🎯
FRQ-Style Task 2 — isAlphabetical
Prompt. Write a static method isAlphabetical that returns true if every letter of word is the same as, or comes after, the letter before it in Java String order, and false otherwise.
| Call | Why | Returns |
|---|---|---|
isAlphabetical("almost") | a, l, m, o, s, t never go backward | true |
isAlphabetical("hello") | "e" comes before "h" | false |
isAlphabetical("Ghost") | uppercase "G" comes before every lowercase letter | true |
Solution
public static boolean isAlphabetical(String word) {
for (int i = 0; i < word.length() - 1; i++) {
String current = word.substring(i, i + 1);
String next = word.substring(i + 1, i + 2);
if (current.compareTo(next) > 0) {
return false;
}
}
return true;
}
- Return false early. One out-of-order pair is enough to answer the question.
- Return true only after the loop. You can only say "every pair is in order" once you have checked every pair.
The classic mistake
if (current.compareTo(next) > 0) {
return false;
} else {
return true; // returns after checking only the first pair
}
With this version, isAlphabetical("abca") returns true: the first pair "a", "b" is in order, so the method returns before it ever reaches "c", "a".
Applied Recall ✍️
-
Using the correct isAlphabetical, what does
isAlphabetical("Ghost")return? (true or false) -
What does
countDoubles("aaabb")return? -
How many times does the correct isAlphabetical evaluate
current.compareTo(next)when called with"bear"?
Common FRQ Deductions on String Methods
| Mistake | Why it costs points |
|---|---|
| Comparing Strings with == | compares references, not contents |
| Loop bound one too far | substring throws when the end index passes the length |
| Returning inside the loop on both branches | the method stops after one check |
| Printing the answer instead of returning it | the method must return a value to its caller |
| Never using the return value of substring | Strings are immutable; the result must be stored or used |
| Calling a method on a parameter that might be null | throws NullPointerException (rare on the exam, but check the preconditions) |
🎯 AP Connection: Write with the methods on the Java Quick Reference:
length,substring,indexOf,equals, andcompareTo. They are enough for every String task the exam sets, and readers know exactly what they do.
Part 7: Synthesis Review
🔤 Strings & Objects
Part 7 of 7 — Synthesis Review
This part ties the topic together: what a String object is, how the five Quick Reference methods behave, and how they combine inside loops. Use the tables as a checklist, then test yourself on mixed questions.
The Topic on One Page
| Idea | Key fact | Typical trap |
|---|---|---|
| String objects (Part 2) | a variable holds a reference; create with a literal or new String(...) | treating "" and null as the same |
| Immutability (Parts 1, 2) | methods return new Strings; reassign to keep the result | s.substring(1); on its own line changes nothing |
| Concatenation (Part 2) | left to right; once a String appears, + joins text | 1 + 2 + "x" is "3x", but "x" + 1 + 2 is "x12" |
| Equality (Part 2) | equals compares characters; == compares references | == on Strings built by substring or + |
| substring (Parts 1, 3) | characters a to b - 1; length b - a; legal when 0 <= a <= b <= length | counting the end index as included |
| indexOf (Parts 1, 3) | first index of the target, or -1 | passing -1 into substring |
| compareTo (Parts 1, 4) | sign only; first difference decides; prefix first | uppercase before lowercase; "10" before "9" |
| Traversal (Part 5) | i < s.length() with substring(i, i + 1) | i <= s.length() throws on the last pass |
| Windows (Part 5) | i <= s.length() - len with substring(i, i + len) | a strict < skips the last window |
🔑 Key Concept: Nearly every String question reduces to three skills: number the indices, decide whether each operation compares or builds, and check every substring call against the bounds rule.
A Tracing Checklist
- Number the indices under each String, starting at 0. Note the length.
- For each indexOf, record the index, or -1 if the target is missing. Remember which String the index belongs to.
- For each substring, write
aandb, confirm0 <= a <= b <= length, and countb - acharacters. - For each +, decide whether it adds or concatenates, working left to right.
- For each comparison, ask: contents (equals, compareTo) or references (==)?
- For each loop, build a trace table with
i, the piece examined, and the accumulator, and check the last value ofi.
Worked Example: Putting It Together
String s = "data-science";
int dash = s.indexOf("-");
String left = s.substring(0, dash);
String right = s.substring(dash + 1);
String initials = left.substring(0, 1) + right.substring(0, 1);
System.out.println(initials + left.compareTo(right));
| Step | Value |
|---|---|
dash | 4 ("d a t a" occupy indices 0 to 3) |
left | "data" |
right | "science" |
initials | "d" + "s" = "ds" |
left.compareTo(right) | "d" vs "s": negative |
The program prints ds followed by some negative number. Because the exact value is not something the AP exam asks you to predict, a well-written question would print initials + (left.compareTo(right) < 0) instead, which gives dstrue. The parentheses matter: without them, Java would try to compare a String with 0 and the line would not compile.
Mixed Review 1 🎯
Segment A
String s = "Programming";
int a = s.indexOf("g");
int b = s.indexOf("m");
System.out.println(s.substring(a, b) + (b - a));
Segment B
String s = "planet";
s.substring(2);
s += "s";
System.out.println(s);
Error Catalogue
| Symptom | Likely cause | Fix |
|---|---|---|
| StringIndexOutOfBoundsException | a substring index is negative, past the length, or start is after end; often a -1 from indexOf | check the bounds rule; guard indexOf results with >= 0 |
| NullPointerException | a method was called on a String variable holding null | make sure the variable refers to an object first |
| A comparison is false although the text matches | == was used | use equals |
| The String "did not change" | the return value of a method was not stored | write s = s.substring(...) |
Unexpected order, such as "Zoo" before "ant" | Unicode order: uppercase before lowercase | expected behavior of compareTo |
| A count is one too low | the window loop stops before the last window | use i <= s.length() - len |
| The result is the original String, not the reverse | appended instead of prepended | reversed = letter + reversed |
| The result starts with "null" | the accumulator started as null | start the accumulator at "" |
🎯 AP Connection: If a trace seems to need an impossible index, look for an exception among the answer choices before assuming you made an arithmetic slip.
Quick Evaluation 🔍
Mixed Review 2 🎯
Segment C
String s = "a1b22c333";
String letters = "";
int digits = 0;
for (int i = 0; i < s.length(); i++) {
String piece = s.substring(i, i + 1);
if ("0123456789".indexOf(piece) >= 0) {
digits++;
} else {
letters += piece;
}
}
System.out.println(letters + digits);
Where Strings Go Next
- Selection and iteration (Unit 2): the traversal patterns from Part 5 are the standard String algorithms of the course: counting, filtering, reversing, and finding substrings with a property.
- Writing classes: a method that builds and returns a String from an object's fields uses the same concatenation rules from Part 2, including left-to-right evaluation.
- Data collections: arrays and lists of Strings are searched with equals and ordered with compareTo, using exactly the conditions from Part 4.
Final Self-Check
- Can you explain why
new String("hi") == new String("hi")is false? - Can you write the expression for the last three characters of any String of length 3 or more?
- Can you state the bounds rule for
substring(a, b)from memory? - Can you predict the sign of
"Mars".compareTo("mars")? - Can you write a loop that counts how many times
"the"appears in a sentence, overlaps included?
If any answer is shaky, revisit the part listed beside that idea in the table at the top of this review.