College Board Unit 1
How it works
A character traversal commonly starts i at 0, continues while i < s.length(), and examines s.substring(i, i + 1). Build a result with concatenation, count matching substrings with a counter, or compare characters using equals. Adjacent-pair comparisons need a bound that leaves room for the next character. State whether pattern matches may overlap and require a nonempty target when a repeated search advances by the target length.
Choose bounds that match the comparison: adjacent-pair loops must stop one index early.
Common error
Running an adjacent-pair loop to the final index, which reads past the end.
Worked example
Java
String text = "level";
int count = 0;
for (int i = 0; i < text.length(); i++) {
if (text.substring(i, i + 1).equals("e")) count++;
}
System.out.println(count);Output
2The traversal visits all five indices and counts matches at indices 1 and 3.
Exercises
4.4.1 · Trace
Determine the exact output. Explain the Java rule or state changes that produce it.
Java
String text = "dog";
String result = "";
for (int i = text.length() - 1; i >= 0; i--) {
result += text.substring(i, i + 1);
}
System.out.println(result);Show solution
Output
godThe loop reads indices 2, 1, and 0 in that order.
4.4.2 · Write code
Write public static String removeA(String text), returning the text with every lowercase "a" omitted. Preserve the order of the remaining characters.
Show solution
One valid solution is shown below. Other implementations satisfying the contract are also valid.
Java
public static String removeA(String text) {
String result = "";
for (int i = 0; i < text.length(); i++) {
String letter = text.substring(i, i + 1);
if (!letter.equals("a")) result += letter;
}
return result;
}Check your code
Java
System.out.println(removeA("banana"));
System.out.println("[" + removeA("") + "]");Expected output
bnn
[]