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.

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.

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.

Visual Explanation — String Anatomy

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()).

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
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)
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
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
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.

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.

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().
Summary of common string processing patterns and their associated methods
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()

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 VariablesWe 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
Step 2 — Extract Each CharacterInside 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
Step 3 — Test for Vowel MembershipWe 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
Step 4 — Trace All IterationsTracing 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 CodeThe 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.

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.

Comparison of Java text representations
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()
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.

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.

How string concepts map to advanced AP CS A topics
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

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.

Practice Problems

1
Consider the following code segment: String s = "Java"; String t = s; s = s + "!"; System.out.println(t); What is printed?
2
What is the value of result after the following code executes? String word = "PINEAPPLE"; String result = word.substring(4, 9);
3
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")?
PROBLEM 4APPLIED
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)
PROBLEM 5CRITICAL THINKING
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)

String Manipulation — Key Concepts Review

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