AP Computer Science A • Using Objects and Methods

String Manipulation

Mastering immutable character sequences through the String class API to solve real-world text-processing problems.

AP Computer Science A illustration with code, binary digits, and programming braces
Inside this lesson 10 sections 5 questions 9 figures

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

Languages like SNOBOL and COBOL introduced dedicated string-handling operations, demonstrating the need for first-class text manipulation in programming.

1972 • C and Null-Terminated Arrays

The C language represented strings as arrays of char values terminated by a null byte—efficient but error-prone, leading to widespread buffer overflow vulnerabilities.

1995 • Java's Immutable String Class

Java 1.0 shipped with an immutable String class backed by a Unicode character array, eliminating many safety issues and enabling string interning for performance.

2004 • AP CS A Curriculum Standardization

The College Board formalized 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.

1

Immutability

Once a String is created, its content cannot be changed. Methods like toUpperCase() return a new String; the original remains untouched.
2

Zero-Based Indexing

Each character in a String occupies a position numbered from 0 to length() − 1. Accessing an index outside this range throws a StringIndexOutOfBoundsException.
3

Reference vs. Content Equality

The == operator compares references (memory addresses), not character content. Always use .equals() or .compareTo() for content comparison.
4

String Concatenation

The + operator joins strings and auto-converts primitives. Because strings are immutable, each concatenation creates a new object in memory.
5

AP Quick Reference Methods

The AP exam provides a Quick Reference sheet listing length(), substring(), indexOf(), equals(), and compareTo(). You must know their signatures and behaviors.
✦

KEY TAKEAWAY

Think of a Java String like a printed book. You can read any page (index), count the pages (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

String Anatomy: "HELLO"Index positionsH0E1L2L3O4Key Method Callsstr.length()→ 5str.charAt(1)→ 'E'str.substring(1, 4)→ "ELL"(includes 1, excludes 4)str.indexOf("LL")→ 2str.indexOf("Z")→ -1(not found)str.equals("HELLO")→ true
The diagram above shows the internal layout of the String "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

intlength()int 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)

Stringsubstring(intfrom,intto)String substring(int from, int to)

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

intindexOf(Stringtarget)int indexOf(String target)

Returns the index of the first occurrence of target within the string, or −1 if not found. The search is case-sensitive.

EQUALS / COMPARETO

booleanequals(Stringother)∣intcompareTo(Stringother)boolean equals(String other) | int compareTo(String other)

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

Never use == 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.

Common String Processing PatternsPattern 1: Character Traversalfor (int i = 0; i < str.length(); i++){ String ch = str.substring(i, i+1); // process ch}Visits each character from left to right.Pattern 2: String ReversalString rev = "";for (int i = str.length()-1; i >= 0; i--){ rev += str.substring(i, i+1);}Builds a new string in reverse order.Pattern 3: Accumulator BuildString result = "";for (int i = 0; i < str.length(); i++){ String ch = str.substring(i, i+1); if (!ch.equals(" ")) result += ch;}Selectively copies characters to a new string.Pattern 4: Substring Searchint pos = str.indexOf(target);while (pos != -1){ count++; pos = str.indexOf(target, pos + 1);}Finds all occurrences of a substring.
Four fundamental string processing patterns. Pattern 1 (Character Traversal) and Pattern 3 (Accumulator Build) appear most frequently on the AP exam. Note how each pattern relies on 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().
PatternWhen to UseKey Methods
Character TraversalCount specific characters, validate input, transform case-by-caselength(), substring(i, i+1)
String ReversalPalindrome detection, mirror transformationslength(), substring(i, i+1), concatenation
Accumulator BuildRemove characters, filter, encrypt, encodeequals(), substring(), +
Substring SearchCount occurrences, find-and-replace, word extractionindexOf(), 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. 1

    Step 1 — Set Up Variables

    We declare 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() → 8
  2. 2

    Step 2 — Extract Each Character

    Inside the loop, we extract each character as a one-character String using String ch = str.substring(i, i + 1);. For iteration i = 0, ch is "C"; for i = 1, ch is "O", and so on.
  3. 3

    Step 3 — Test for Vowel Membership

    We check whether 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).
  4. 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. 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.

FeatureStringStringBuilderchar[]
MutabilityImmutable — cannot be changed after creationMutable — supports in-place modificationMutable — individual elements can be reassigned
Concatenation CostO(n) per concatenation — creates a new object each timeO(1) amortized — appends to internal bufferManual management required — no built-in concatenation
Thread SafetyThread-safe (immutability guarantees this)Not thread-safeNot thread-safe
AP Exam StatusFully testedNot testedNot tested
Equality Check.equals() for contentConvert to String firstArrays.equals()

Comparison of Java text representations

✦

KEY TAKEAWAY

On the AP exam, repeated string concatenation in a loop (e.g., 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 ConceptAdvanced Connection
str.substring(i, i+1) traversalArray element access arr[i] — same zero-based indexing
Accumulator concatenation patternArrayList .add() — building a collection element by element
indexOf searchLinear search in arrays — same sentinel return value (−1)
compareTo lexicographic orderingComparable interface and sorting algorithms
Immutability of StringWrapper 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

Consider the following code segment: 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)
The correct answer is B. Because String objects are immutable, 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

What is the value of 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)
The correct answer is A. The string "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

Consider the following method: 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)
The correct answer is B. The loop increments 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 pts
Write the method 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)
Show answer
Rubric (3 points): Point 1 — Loop with indexOf: Uses a loop (while or for) that repeatedly calls 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 pts
Write a method 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)
Show answer
Rubric (4 points): Point 1 — Outer loop to find forbidden words: Uses a loop (e.g., 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.

Varsity Tutors • AP Computer Science A • String Manipulation