String questions on AP Computer Science A often look short, but they reward careful boundary tracing. The most important rule is that substring(start, end) includes the start index and excludes the end index.
The boundary rule
String word = "COMPUTER";
System.out.println(word.substring(1, 4));
The output is OMP. Index 1 is included. Index 4 is not included.
Using indexOf with substring
indexOf returns the first index where a target appears. If the target does not appear, it returns -1.
String phrase = "data structures";
int space = phrase.indexOf(" ");
String first = phrase.substring(0, space);
String second = phrase.substring(space + 1);
Here, first becomes "data" and second becomes "structures". The space + 1 is important because the space itself should not be part of the second word.
The -1 trap
String s = "algorithm";
int location = s.indexOf("z");
System.out.println(s.substring(location));
This causes a runtime error because location is -1. A negative substring index is invalid. In AP CSA code tracing, always check whether indexOf might return -1.
String immutability
String s = "java";
s.toUpperCase();
System.out.println(s);
The output is still java. String methods return new strings. They do not modify the original object. To keep the changed value, assign it back:
s = s.toUpperCase();
AP CSA tracing checklist
- Write the indexes above the characters.
- Remember that the ending substring index is excluded.
- Check whether
indexOfcan return-1. - Remember that Strings are immutable.
