String
Manipulation
Master the essential String methods in Java: extracting, comparing, and transforming text for the AP Computer Science A exam.
What Is a String?
In Java, a String is an immutable sequence of characters. Once created, its contents cannot be changed: every method that seems to modify a String actually returns a new String object.
Immutability: Strings Never Change
When you call a method like toUpperCase() or substring(), the original String stays the same. A brand-new String is returned. If you don't store the result, it is lost.
Zero-Based Indexing
Each character in a String has an index starting at 0. The last character is at index \( \text{length()} - 1 \). Accessing an index outside this range throws a StringIndexOutOfBoundsException.
Core String Methods
The substring() Method
substring(beginIndex, endIndex) extracts characters starting at beginIndex up to but not including endIndex. There is also a one-argument form: substring(beginIndex) goes from that index to the end.
equals() vs ==
Lexicographic Order: compareTo()
str1.compareTo(str2) returns an integer based on lexicographic (dictionary) order. It compares character by character using Unicode values.
How to Apply String Methods
Example 1: Extracting a Substring
Problem: Given "Computer", extract the word "put".
Example 2: Searching with indexOf()
Problem: Find the position of "Science" in the String "Computer Science A", then extract it.
Example 3: Traversing a String
Problem: Count how many times the letter 'a' appears in "banana".
Concatenation with +
The + operator joins Strings together. When you concatenate a non-String value (like an int), Java automatically converts it to a String first.
Common Mistakes
Method Quick Reference
| Method | Returns | Example |
|---|---|---|
| length() | int | "Hello".length() → 5 |
| charAt(i) | char | "Hello".charAt(1) → 'e' |
| substring(a, b) | String | "Hello".substring(1,4) → "ell" |
| indexOf(str) | int | "Hello".indexOf("ll") → 2 |
| equals(other) | boolean | "Hi".equals("Hi") → true |
| compareTo(other) | int | "a".compareTo("b") → negative |
Question 1 of 5
What is the output of the following code?
String s = "AP Exam";
System.out.println(s.substring(3, 7));
Question 2 of 5
What does the following code print?
String s = "hello";
s.toUpperCase();
System.out.println(s);
Question 3 of 5
What is the value of result after this code executes?
String s = "Java";
int result = s.indexOf("va");
Question 4 of 5
What does the following expression evaluate to?
2 + 3 + "CS" + 4 + 5
Question 5 of 5
Which code correctly checks if String s ends with the character 'e'?