Loading
Mastering immutable character sequences through the String class API to solve real-world text-processing problems.
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.
char values terminated by a null byte—efficient but error-prone, leading to widespread buffer overflow vulnerabilities.String class backed by a Unicode character array, eliminating many safety issues and enabling string interning for performance.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.
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.
String is created, its content cannot be changed. Methods like toUpperCase() return a new String; the original remains untouched.0 to length() − 1. Accessing an index outside this range throws a StringIndexOutOfBoundsException.== operator compares references (memory addresses), not character content. Always use .equals() or .compareTo() for content comparison.+ operator joins strings and auto-converts primitives. Because strings are immutable, each concatenation creates a new object in memory.length(), substring(), indexOf(), equals(), and compareTo(). You must know their signatures and behaviors.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."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()).
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.
"" has length 0. The valid index range is [0, length() − 1].from (inclusive) to index to (exclusive). The length of the result is to − from. Throws StringIndexOutOfBoundsException if indices are out of range.target within the string, or −1 if not found. The search is case-sensitive.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.== 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.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() |
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.
String str = "COMPUTER"; and int count = 0;. We also define a helper string containing all vowels: String vowels = "AEIOU";. The length of str is 8, so our loop will iterate with i from 0 to 7.str.length() → 8String ch = str.substring(i, i + 1);. For iteration i = 0, ch is "C"; for i = 1, ch is "O", and so on.vowels.indexOf(ch) != -1. If indexOf returns a value ≥ 0, then ch is a vowel and we increment count. For "C", vowels.indexOf("C") returns −1 (not a vowel). For "O", vowels.indexOf("O") returns 3 (is a vowel).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.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() |
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.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 |
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.
String s = "Java";
String t = s;
s = s + "!";
System.out.println(t);
What is printed?result after the following code executes?
String word = "PINEAPPLE";
String result = word.substring(4, 9);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")?removeAllOccurrences 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)censor 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)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.
Keep learning with more lessons from the same subject.