SECTION 1
Historical Context & Motivation
Text processing is one of the oldest and most enduring problems in computer science. From the earliest punched-card systems that encoded census data as character strings, to modern search engines that parse billions of web pages, the ability to represent, inspect, and transform sequences of characters has remained central to software development. Java's String class was designed from the outset to provide a robust, immutable abstraction over character data, reflecting lessons learned from decades of language evolution. Understanding why strings behave the way they do in Java—and how to manipulate them efficiently—is essential both for the AP Computer Science A exam and for professional software engineering.
1960s • Early String Processing
1972 • C and Null-Terminated Arrays
char values terminated by a null byte—efficient but error-prone, leading to widespread buffer overflow vulnerabilities.1995 • Java's Immutable String Class
String class backed by a Unicode character array, eliminating many safety issues and enabling string interning for performance.2004 • AP CS A Curriculum Standardization
String methods like substring, indexOf, and equals as testable content in the AP Computer Science A Quick Reference.The central question this lesson addresses is: how do we use the methods of Java's String class to extract, compare, and transform textual data—without modifying the original string? Because String objects in Java are immutable, every manipulation creates a new String rather than altering the existing one. This design choice has profound implications for how you write code on the AP exam.
SECTION 2
Core Principles & Definitions
Before diving into individual methods, it is important to internalize the foundational ideas that govern how String objects behave in Java. These principles appear repeatedly on the AP exam—both in multiple-choice tracing questions and in free-response problems that require you to build or analyze string-processing algorithms.
Immutability
String is created, its content cannot be changed. Methods like toUpperCase() return a new String; the original remains untouched.Zero-Based Indexing
0 to length() − 1. Accessing an index outside this range throws a StringIndexOutOfBoundsException.Reference vs. Content Equality
== operator compares references (memory addresses), not character content. Always use .equals() or .compareTo() for content comparison.String Concatenation
+ operator joins strings and auto-converts primitives. Because strings are immutable, each concatenation creates a new object in memory.AP Quick Reference Methods
length(), substring(), indexOf(), equals(), and compareTo(). You must know their signatures and behaviors.KEY TAKEAWAY
length()), photocopy a chapter (substring()), or search the index (indexOf()), but you can never erase or rewrite the ink on an existing page. Every edit produces a brand-new book. This is immutability.SECTION 3
Visual Explanation — String Anatomy
"HELLO" with each character at its zero-based index. The method call results demonstrate the core String API behavior, including substring's half-open interval semantics and indexOf returning −1 when a target is not found.Notice that substring(1, 4) uses a half-open interval: the start index is inclusive and the end index is exclusive. This convention is consistent throughout the Java standard library and is one of the most common sources of off-by-one errors on the AP exam. A useful mnemonic is to think of the end index as pointing to the first character not included in the result. You can also use the one-argument form, substring(k), which returns all characters from index k to the end of the string—equivalent to substring(k, str.length()).
SECTION 4
How It Works — The String API in Depth
The AP Computer Science A Quick Reference lists a specific set of String methods you are expected to know. While Java's String class provides dozens of methods, the exam focuses on a compact but powerful subset. This section formally defines each method's signature, return type, and edge-case behavior.
Method Signatures and Semantics
LENGTH
Returns the number of characters in the string. An empty string "" has length 0. The valid index range is [0, length() − 1].
SUBSTRING (TWO-ARG)
Returns the substring from index from (inclusive) to index to (exclusive). The length of the result is to − from. Throws StringIndexOutOfBoundsException if indices are out of range.
INDEXOF
Returns the index of the first occurrence of target within the string, or −1 if not found. The search is case-sensitive.
EQUALS / COMPARETO
equals returns true if and only if every character matches. compareTo returns 0 if equal, a negative value if the calling string is lexicographically before other, and a positive value otherwise. Comparison is based on Unicode values.
AP Exam Trap
== to compare String content. The expression new String("cat") == new String("cat") evaluates to false because == checks whether two references point to the same object in memory, not whether the characters match. The AP exam regularly tests this distinction in tracing questions.SECTION 5
Common String Processing Patterns
String manipulation on the AP exam frequently revolves around a small set of recurring algorithmic patterns. Understanding these patterns allows you to recognize and solve problems quickly, whether the task is extracting words, reversing characters, or searching for substrings. The diagram below illustrates the most important traversal and extraction patterns, and the table that follows summarizes the code idioms you should internalize.
substring rather than charAt for character extraction—both approaches are valid, but substring returns a String which can be directly concatenated or compared with .equals().| Pattern | When to Use | Key Methods |
|---|---|---|
| Character Traversal | Count specific characters, validate input, transform case-by-case | length(), substring(i, i+1) |
| String Reversal | Palindrome detection, mirror transformations | length(), substring(i, i+1), concatenation |
| Accumulator Build | Remove characters, filter, encrypt, encode | equals(), substring(), + |
| Substring Search | Count occurrences, find-and-replace, word extraction | indexOf(), substring() |
Summary of common string processing patterns and their associated methods
SECTION 6
Worked Example — Counting Vowels
Let us trace through a complete example that counts the number of vowels in a given string. This problem integrates character traversal, substring extraction, and indexOf for membership testing—three of the most heavily tested techniques on the AP exam.
Count Vowels in "COMPUTER"
- 1
Step 1 — Set Up Variables
We declareString str = "COMPUTER";andint count = 0;. We also define a helper string containing all vowels:String vowels = "AEIOU";. The length ofstris 8, so our loop will iterate withifrom 0 to 7.str.length() → 8 - 2
Step 2 — Extract Each Character
Inside the loop, we extract each character as a one-character String usingString ch = str.substring(i, i + 1);. For iterationi = 0,chis"C"; fori = 1,chis"O", and so on. - 3
Step 3 — Test for Vowel Membership
We check whethervowels.indexOf(ch) != -1. IfindexOfreturns a value ≥ 0, thenchis a vowel and we incrementcount. For "C",vowels.indexOf("C")returns−1(not a vowel). For "O",vowels.indexOf("O")returns3(is a vowel). - 4
Step 4 — Trace All Iterations
Tracing through "COMPUTER" character by character: C(no), O(yes→1), M(no), P(no), U(yes→2), T(no), E(yes→3), R(no). The vowels found are O, U, and E at indices 1, 4, and 6 respectively.count = 3 - 5
Step 5 — Complete Code
The complete method is:public static int countVowels(String str) { String vowels = "AEIOU"; int count = 0; for (int i = 0; i < str.length(); i++) { String ch = str.substring(i, i + 1); if (vowels.indexOf(ch) != -1) { count++; } } return count; }This pattern—traversal plus membership test—generalizes to any character-classification problem.
SECTION 7
String vs. Other Text Types
While the AP exam focuses almost exclusively on the String class, it is useful to understand how String compares to other text representations you may encounter in Java programming. The table below highlights the trade-offs between String, StringBuilder, and character arrays. Although StringBuilder and char[] are not tested on the AP exam, understanding why String is immutable deepens your conceptual grasp and prepares you for college-level courses.
| Feature | String | StringBuilder | char[] |
|---|---|---|---|
| Mutability | Immutable — cannot be changed after creation | Mutable — supports in-place modification | Mutable — individual elements can be reassigned |
| Concatenation Cost | O(n) per concatenation — creates a new object each time | O(1) amortized — appends to internal buffer | Manual management required — no built-in concatenation |
| Thread Safety | Thread-safe (immutability guarantees this) | Not thread-safe | Not thread-safe |
| AP Exam Status | Fully tested | Not tested | Not tested |
| Equality Check | .equals() for content | Convert to String first | Arrays.equals() |
Comparison of Java text representations
KEY TAKEAWAY
result += ch) is perfectly acceptable and expected. In production-grade Java, you would use StringBuilder for better performance, but the exam prioritizes clarity and correctness over optimization. Focus on getting the logic right using String methods.SECTION 8
Connections to Advanced Topics
String manipulation is not an isolated topic—it connects deeply to other areas of the AP Computer Science A curriculum and beyond. When you study arrays and ArrayLists, you will encounter analogous indexing and traversal patterns. When you learn about recursion, many classic problems (palindromes, permutations, parsing) rely on substring to decompose strings into smaller pieces. The table below maps string concepts to their advanced counterparts.
| String Concept | Advanced Connection |
|---|---|
str.substring(i, i+1) traversal | Array element access arr[i] — same zero-based indexing |
| Accumulator concatenation pattern | ArrayList .add() — building a collection element by element |
indexOf search | Linear search in arrays — same sentinel return value (−1) |
compareTo lexicographic ordering | Comparable interface and sorting algorithms |
| Immutability of String | Wrapper classes (Integer, Double) are also immutable; understanding why helps with autoboxing |
How string concepts map to advanced AP CS A topics
Looking ahead to college-level computer science, string manipulation forms the foundation for regular expressions, lexical analysis in compilers, natural language processing, and bioinformatics (where DNA sequences are essentially strings over a four-character alphabet). The traversal and search patterns you master here will remain relevant throughout your computing career.
SECTION 9
Practice Problems
Question 1: CONCEPTUAL
String s = "Java";
String t = s;
s = s + "!";
System.out.println(t);
What is printed?- A.
Java! - B.
Java - C. A compile-time error occurs
- D. A runtime error occurs
Show answer (B)
s = s + "!" creates a brand-new String "Java!" and reassigns the reference s to point to it. The variable t still references the original "Java" object, which was never modified. A is wrong because it assumes the original String object was mutated in place. C is wrong because the code is syntactically valid. D is wrong because no exception is thrown—concatenation works correctly.Question 2: BASIC CALCULATION
result after the following code executes?
String word = "PINEAPPLE";
String result = word.substring(4, 9);- A.
"APPLE" - B.
"APPL" - C.
"EAPPL" - D.
"NAPPLE"
Show answer (A)
"PINEAPPLE" has indices: P(0) I(1) N(2) E(3) A(4) P(5) P(6) L(7) E(8). substring(4, 9) extracts characters at indices 4 through 8 (inclusive start, exclusive end), yielding "APPLE". B is wrong because it omits the last character (index 8), as if the end index were 8 rather than 9. C is wrong because it incorrectly starts at index 3. D is wrong because it starts at index 2.Question 3: INTERMEDIATE
public static String mystery(String s) {
String result = "";
for (int i = 0; i < s.length(); i += 2) {
result += s.substring(i, i + 1);
}
return result;
}
What is returned by mystery("ABCDEFG")?- A.
"BDFG" - B.
"ACEG" - C.
"ABCD" - D.
"ACE"
Show answer (B)
i by 2 each iteration, so it visits indices 0, 2, 4, and 6. The characters at those positions in "ABCDEFG" are A, C, E, and G, producing "ACEG". A is wrong because it selects odd-indexed characters (1, 3, 5) plus the last character. C is wrong because it takes the first four characters consecutively rather than every other character. D is wrong because it stops too early—index 6 is still within the length of 7, so "G" is included.Question 4: APPLIED
3 ptsremoveAllOccurrences that takes two String parameters, str and target, and returns a new String with all occurrences of target removed from str. For example, removeAllOccurrences("banana", "an") should return "ba". You may not use the replace method.
Complete the method signature:
public static String removeAllOccurrences(String str, String target)Show answer
str.indexOf(target) to find the position of the next occurrence, terminating when indexOf returns −1.
Point 2 — Correct removal via substring concatenation: Constructs the new string by concatenating str.substring(0, pos) with str.substring(pos + target.length()), effectively skipping over the found occurrence.
Point 3 — Returns correct result: Returns the modified string. Handles edge cases such as no occurrences (returns original string) and overlapping matches.
Sample Solution:
public static String removeAllOccurrences(String str, String target) {
int pos = str.indexOf(target);
while (pos != -1) {
str = str.substring(0, pos) + str.substring(pos + target.length());
pos = str.indexOf(target);
}
return str;
}Question 5: CRITICAL THINKING
4 ptscensor that takes a String message and a String word, and returns a new string in which every occurrence of word in message has been replaced by a sequence of "*" characters of the same length as word. All other characters in the message should remain unchanged.
For example:
• censor("THE APPLE DOES NOT FALL FAR FROM THE TREE", "THE") returns "*** APPLE DOES NOT FALL FAR FROM *** TREE"
• censor("BANANA BANDANA", "AN") returns "B****A B**D**A"
You may use String methods length(), substring(), indexOf(), equals(), and string concatenation (+).
Complete the method:
public static String censor(String message, String word)Show answer
while with indexOf) to repeatedly search for occurrences of the forbidden word in the message. The loop correctly terminates when no more occurrences are found (indexOf returns -1).
Point 2 — Building the replacement string of asterisks: Constructs a string of "*" characters whose length equals word.length(). Uses a loop or repeated concatenation to build the correct number of asterisks.
Point 3 — Correct use of substring to replace: Uses substring to extract the portions of the message before and after the forbidden word, and concatenates them with the asterisks to form the new message. The indices used in substring must be correct (before: substring(0, pos), after: substring(pos + word.length())).
Point 4 — Handles multiple occurrences and returns correct result: The method correctly replaces all occurrences of the forbidden word (not just the first), and returns the final censored string. Produces correct output for the given examples, including the case with multiple occurrences.
Sample Solution:
public static String censor(String message, String word) {
String stars = "";
for (int i = 0; i < word.length(); i++) {
stars += "*";
}
int pos = message.indexOf(word);
while (pos >= 0) {
message = message.substring(0, pos) + stars + message.substring(pos + word.length());
pos = message.indexOf(word);
}
return message;
}
Trace of first example:
message = "THE APPLE DOES NOT FALL FAR FROM THE TREE", word = "THE"
stars = "***"
Iteration 1: pos = 0 → "***" + " APPLE DOES NOT FALL FAR FROM THE TREE"
message = "*** APPLE DOES NOT FALL FAR FROM THE TREE"
Iteration 2: pos = 33 → "*** APPLE DOES NOT FALL FAR FROM " + "***" + " TREE"
message = "*** APPLE DOES NOT FALL FAR FROM *** TREE"
Iteration 3: pos = -1 → loop ends
Return: "*** APPLE DOES NOT FALL FAR FROM *** TREE"SUMMARY
String Manipulation — Key Concepts Review
Summary
Java's String class represents immutable sequences of characters, meaning every manipulation—concatenation, case conversion, or extraction—produces a new String object rather than modifying the original. Characters are accessed via zero-based indexing, where valid indices range from 0 to length() − 1. The AP Quick Reference methods— length(), substring(), indexOf(), equals(), and compareTo()—form the foundation of all string processing on the exam. Always use .equals() for content comparison, never ==.
The four essential patterns— character traversal, string reversal, accumulator build, and substring search—cover the vast majority of exam questions. Remember that substring(from, to) uses a half-open interval (inclusive start, exclusive end), and that indexOf returns −1 when the target is not found. Master these methods and patterns, and you will be well-equipped for both the multiple-choice and free-response sections of the AP Computer Science A exam.