College Board Unit 1
How it works
String positions are zero-based, so the first character sits at index 0 and the last sits at length() - 1. The charAt method returns the character at a position, and length() is a method with parentheses, unlike the length field on an array. Any index that is negative or greater than or equal to length() throws a StringIndexOutOfBoundsException.
Write the index beneath each character before evaluating any call.
Common error
Using length as an index, which is the standard out-of-bounds error.
Worked example
Java
String word = "JAVA";
System.out.println(word.length());
System.out.println(word.substring(3, 4));Output
4
ALength counts characters; the final valid position is one less than the length.
Exercises
4.1.1 · Trace
Determine the exact output. Explain the Java rule or state changes that produce it.
Java
String word = "code";
System.out.println(word.substring(0, 1) + word.substring(word.length() - 1));Show solution
Output
ceThe first slice includes index 0 only. The one-argument slice continues from index 3 to the end.
4.1.2 · Write code
Write public static String ends(String text). Assume text is nonempty. Return the first and last characters joined together; a one-character input contributes that character twice.
Show solution
One valid solution is shown below. Other implementations satisfying the contract are also valid.
Java
public static String ends(String text) {
return text.substring(0, 1) + text.substring(text.length() - 1);
}Check your code
Java
System.out.println(ends("Java"));
System.out.println(ends("Q"));Expected output
Ja
QQ