Skip to content
🎯⭐ INTERACTIVE LESSON

Strings & Objects

Learn step-by-step with interactive practice!

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)

MethodReturn TypeDescriptionExample
length()intNumber of characters"hello".length() → 5
substring(start)StringFrom start to end"hello".substring(2) → "llo"
substring(start, end)StringFrom start to end-1"hello".substring(1,4) → "ell"
indexOf(str)intFirst occurrence (-1 if not found)"hello".indexOf("ll") → 2
equals(str)booleanContent comparison"hi".equals("hi") → true
compareTo(str)intLexicographic: 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 index a but EXCLUDES index b

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 ValueMeaning
NegativeCalling string comes before parameter alphabetically
0Strings are equal
PositiveCalling string comes after parameter alphabetically
"apple".compareTo("banana")  // Negative (a < b)
"cat".compareTo("cat")       // 0 (equal)
"dog".compareTo("cat")       // Positive (d > c)

Escape Sequences

SequenceMeaning
\\Backslash
\"Double quote inside a String
\nNewline

These three are the only escape sequences in the AP Java subset.

Applied Recall ✍️

  1. String indexing in Java starts at _______ (not 1).

  2. Strings in Java are _______, meaning their content cannot be changed after creation.

  3. 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?YesNo
length()returns 0throws NullPointerException
In concatenation, "Hi " + sgives "Hi "gives "Hi null"
Typical usestarting value for a String you will build with +="no value yet"

💡 When you build a String in a loop, start from "", never from null. Starting from null puts the four letters "null" at the front of your result.

Concatenation with Other Types

Three rules decide what + does:

  1. If either operand is a String, + means concatenation. The other operand is converted to its String form first.
  2. Operators of the same precedence are evaluated left to right, so whether a + adds or concatenates depends on what has been built so far.
  3. *, / and % happen before +, and parentheses force anything inside them to happen first.
ExpressionStepsResult
"Total: " + 3 + 4"Total: 3" + 4"Total: 34"
3 + 4 + " total"7 + " total""7 total"
"Total: " + (3 + 4)parentheses first"Total: 7"
"Avg " + 7 / 2int division first: 3"Avg 3"
"Avg " + 7.0 / 2double division first: 3.5"Avg 3.5"
"x" + 2.0a double always shows a decimal point"x2.0"
"ok? " + (5 > 3)boolean becomes "true""ok? true"

Two more facts:

  • "Total: " + 3 - 4 does 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);
StepOperationValue so far
1a + b (both int)7
27 + " 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 ==

TestQuestion it asksUse it for Strings?
a == bDo 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
LineWhy
t.length()t refers to a real object with no characters
"x" + sconcatenation 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 when answer is null, while answer.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 ✍️

  1. What is printed by System.out.println(1 + 2 + "A" + 1 + 2);?

  2. After these statements run, what is s.length()?

String s = "ab";
s += s;
s += "c";
  1. To check whether two Strings contain the same characters, call the _______ method.

Part 2 Summary

IdeaRemember
String variableshold a reference to an object (or null)
"" vs nullempty String is an object; null is no object
Concatenationleft to right; once a String appears, + joins text
Precedence*, /, % and parentheses happen before +
+= on a Stringbuilds a new object and reassigns the variable
Comparing contentsequals, never ==
Method call on nullNullPointerException 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 indices a through b - 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
GoalExpressionResult for "planet"
First characters.substring(0, 1)"p"
Last characters.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 characters.substring(1)"lanet"
Everything except the last characters.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 + 2 skips both the comma (index 8) and the space (index 9). Using comma + 1 would 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);
}
codedashprefix
"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):

CallResultReason
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)exceptionend is past the length
s.substring(3, 2)exceptionstart is after end
s.substring(-1)exceptionnegative start
s.substring(s.indexOf("x"))exceptionindexOf gave -1

🎯 AP Connection: The length itself is a legal end index but never a legal single-character index. s.substring(s.length()) is "", while s.substring(s.length(), s.length() + 1) throws. Watch for that difference in loop bounds in Part 5.

Applied Recall ✍️

String s = "stadium";
  1. What does s.indexOf("dium") return?

  2. What is s.substring(s.indexOf("a") + 1).length()?

  3. What is the largest int k for which s.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

TaskPattern
Character at is.substring(i, i + 1)
Last characters.substring(s.length() - 1)
Text before a markers.substring(0, s.indexOf(marker))
Text after a one-character markers.substring(s.indexOf(marker) + 1)
Replace first occurrencebefore + new + after using p + t.length()
Missing markerindexOf gives -1; check >= 0 before cutting
Legal call0 <= 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, a comes first; if it is positive, b comes first; if it is 0, the Strings are identical.

How compareTo Decides

To evaluate a.compareTo(b), Java walks both Strings from index 0:

  1. Compare the characters at the same index.
  2. 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 is b.
  3. If one String runs out while every character so far has matched, the shorter String comes first (it is a prefix of the other).
  4. If both run out at the same time, the Strings are equal and the result is 0.

Worked Table

CallDeciding stepSignMeaning
"cart".compareTo("care")index 3: "t" vs "e"positive"cart" comes after "care"
"bat".compareTo("bath")"bat" runs out firstnegativea prefix comes first
"Zebra".compareTo("apple")index 0: "Z" vs "a"negativeuppercase comes before lowercase
"apple".compareTo("Apple")index 0: "a" vs "A"positivelowercase comes after uppercase
"10".compareTo("9")index 0: "1" vs "9"negativetext order, not numeric order
"dog".compareTo("dog")no difference, same length0equal

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:

GroupUnicode valuesExample
space32" "
digits48 to 57"0" through "9"
uppercase letters65 to 90"A" through "Z"
lowercase letters97 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 testWrite
a comes before ba.compareTo(b) < 0
a comes after ba.compareTo(b) > 0
a and b are the same texta.compareTo(b) == 0 or a.equals(b)
a comes before b or matches ita.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);
StepComparisonSignClause
1"ant".compareTo("Bee"): "a" vs "B"positivefalse
2short-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

PointDetail
Return typescompareTo returns an int; equals returns a boolean. if (a.compareTo(b)) does not compile.
AgreementFor Strings, a.compareTo(b) == 0 is true exactly when a.equals(b) is true.
CaseBoth are case-sensitive: "Cat".equals("cat") is false and their compareTo is not 0.
Exact valuesTest only the sign: < 0, > 0, == 0.
null argumenta.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

RuleExample
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 texta.compareTo(b) == 0, same as a.equals(b)
Sign onlynever 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
}
  • i runs from 0 to s.length() - 1, the last legal single-character index.
  • s.substring(i, i + 1) is the one-character String at index i. On the last pass, i + 1 equals s.length(), which is a legal end index.
  • Each letter is a String, so test it with equals or indexOf, 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).

CallVowels foundReturns
countVowels("education")e, u, a, i, o5
countVowels("rhythm")none0
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:

CallWindows that matchReturns
countOccurrences("banana", "ana")start at 1 and 32
countOccurrences("aaaa", "aa")start at 0, 1, and 23
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;
}
iletterreversed 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);
Passps after the removal
10"-la-land"
21"--land"
32"--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

BugWhat 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 startindex 0 is never examined
i < s.length() - len in a window loopthe last window is skipped
i < s.length() with substring(i, i + len) and len of 2 or morethrows once i + len passes the length
reversed = reversed + lettercopies 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 i the loop allows and plug it into every substring call. The end index may equal s.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 ✍️

  1. What does countVowels("audio") return?

  2. How many times does the loop body in countOccurrences run for countOccurrences("abcdefgh", "abc")?

  3. Type the word the prepend loop from Algorithm 4 produces when s is "flow" (no quotation marks).

Part 5 Summary

AlgorithmLoop boundKey line
Examine each letteri < s.length()String letter = s.substring(i, i + 1);
Count a propertyi < s.length()if ("aeiou".indexOf(letter) >= 0) count++;
Count or find a substringi <= s.length() - lens.substring(i, i + len).equals(target)
Filteri < s.length()if (!current.equals(letter)) result += current;
Reversei < s.length()reversed = letter + reversed;
Remove every copywhile (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

StepDo this
1Write the indices under every String in the code.
2For each substring call, write the start and end and check 0 <= a <= b <= length.
3For loops, make a trace table: i, the piece examined, and the accumulator.
4For each comparison, ask whether it compares contents (equals, compareTo) or references (==).
5Find 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.

CallMatching pairsReturns
countDoubles("bookkeeper")oo, kk, ee3
countDoubles("aaabb")aa (0 and 1), aa (1 and 2), bb3
countDoubles("x")none0
countDoubles("")none0

Plan before you write

  • Each pass looks at two neighbors, so the last legal i is str.length() - 2. The loop condition is i < str.length() - 1.
  • Pull out the neighbors with substring(i, i + 1) and substring(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

PointEarned by
Traversalvisits every adjacent pair with no out-of-bounds call
Extractiongets the two neighbors as one-character Strings
Comparisoncompares contents with equals (not ==)
Resultinitializes 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.

CallWhyReturns
isAlphabetical("almost")a, l, m, o, s, t never go backwardtrue
isAlphabetical("hello")"e" comes before "h"false
isAlphabetical("Ghost")uppercase "G" comes before every lowercase lettertrue

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 ✍️

  1. Using the correct isAlphabetical, what does isAlphabetical("Ghost") return? (true or false)

  2. What does countDoubles("aaabb") return?

  3. How many times does the correct isAlphabetical evaluate current.compareTo(next) when called with "bear"?

Common FRQ Deductions on String Methods

MistakeWhy it costs points
Comparing Strings with ==compares references, not contents
Loop bound one too farsubstring throws when the end index passes the length
Returning inside the loop on both branchesthe method stops after one check
Printing the answer instead of returning itthe method must return a value to its caller
Never using the return value of substringStrings are immutable; the result must be stored or used
Calling a method on a parameter that might be nullthrows NullPointerException (rare on the exam, but check the preconditions)

🎯 AP Connection: Write with the methods on the Java Quick Reference: length, substring, indexOf, equals, and compareTo. 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

IdeaKey factTypical 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 results.substring(1); on its own line changes nothing
Concatenation (Part 2)left to right; once a String appears, + joins text1 + 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 <= lengthcounting the end index as included
indexOf (Parts 1, 3)first index of the target, or -1passing -1 into substring
compareTo (Parts 1, 4)sign only; first difference decides; prefix firstuppercase 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

  1. Number the indices under each String, starting at 0. Note the length.
  2. For each indexOf, record the index, or -1 if the target is missing. Remember which String the index belongs to.
  3. For each substring, write a and b, confirm 0 <= a <= b <= length, and count b - a characters.
  4. For each +, decide whether it adds or concatenates, working left to right.
  5. For each comparison, ask: contents (equals, compareTo) or references (==)?
  6. For each loop, build a trace table with i, the piece examined, and the accumulator, and check the last value of i.

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));
StepValue
dash4 ("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

SymptomLikely causeFix
StringIndexOutOfBoundsExceptiona substring index is negative, past the length, or start is after end; often a -1 from indexOfcheck the bounds rule; guard indexOf results with >= 0
NullPointerExceptiona method was called on a String variable holding nullmake sure the variable refers to an object first
A comparison is false although the text matches== was useduse equals
The String "did not change"the return value of a method was not storedwrite s = s.substring(...)
Unexpected order, such as "Zoo" before "ant"Unicode order: uppercase before lowercaseexpected behavior of compareTo
A count is one too lowthe window loop stops before the last windowuse i <= s.length() - len
The result is the original String, not the reverseappended instead of prependedreversed = letter + reversed
The result starts with "null"the accumulator started as nullstart 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.