Lesson 1.14 · Unit 1 · CED topic 1.15
String methods and indexes
Joining Strings is the easy half. The skill the exam rewards is taking a String apart: pulling out a piece, finding a character, checking whether two Strings are the same, putting them in order. This lesson covers the five String methods on the Java Quick Reference, and the one idea underneath all of them: indexes start at zero.
Learning objective.
- 1.15.B. Develop code to call methods on string objects and determine the result of calling these methods.
Essential knowledge.
- 1.15.B.1. A String object has index values from 0 to one less than the length of the string. Attempting to access indices outside this range will result in a StringIndexOutOfBoundsException.
- 1.15.B.2. The following String methods—including what they do and when they are used—are part of the Java Quick Reference:
int length()returns the number of characters in a String object.String substring(int from, int to)returns the substring beginning at index from and ending at index to - 1.String substring(int from)returns substring(from, length()).int indexOf(String str)returns the index of the first occurrence of str; returns -1 if not found.boolean equals(Object other)returns true if this corresponds to the same sequence of characters as other; returns false otherwise.int compareTo(String other)returns a value < 0 if this is less than other; returns zero if this is equal to other; returns a value > 0 if this is greater than other. Strings are ordered based upon the alphabet.
Outside the course: Using the equals method to compare one String object with an object of a type other than String is outside the scope of the AP Computer Science A course and exam. - 1.15.B.3. A string identical to the single element substring at position index can be created by calling substring(index, index + 1).
Indexes
A String has index values from 0 to one less than its length. The first character is at index 0, and the last is at index length() - 1.
Trying to use an index outside that range throws a StringIndexOutOfBoundsException while the program runs.
The methods on the Java Quick Reference
| Method | Returns | What it does |
|---|---|---|
int length() | int | the number of characters in the String |
String substring(int from, int to) | String | the characters from index from through index to - 1 |
String substring(int from) | String | the same as substring(from, length()): from from to the end |
int indexOf(String str) | int | the index of the first occurrence of str, or -1 if it is not found |
boolean equals(Object other) | boolean | true if this String has the same sequence of characters as other |
int compareTo(String other) | int | negative if this String comes before other, zero if equal, positive if after |
String word = "Computer";
System.out.println(word.length());
System.out.println(word.substring(2, 5));
System.out.println(word.substring(5));
System.out.println(word.indexOf("put"));
System.out.println(word.indexOf("z"));
8 mpu ter 3 -1
Read substring(2, 5) as "start at index 2, stop before index 5": the first index is included and the second is excluded, so you get 5 - 2 = 3 characters.
### One character at a time
The subset has no single-character type. To get the character at a position, take a one-character substring: substring(index, index + 1).
String word = "Computer"; String first = word.substring(0, 1); String last = word.substring(word.length() - 1); System.out.println(first + " " + last);
C r
### Comparing Strings
Use equals to test whether two Strings contain the same characters. compareTo orders Strings by the alphabet: the result is negative, zero, or positive. Only the sign is meaningful; do not depend on the exact number. Capital letters sort before lowercase letters.
System.out.println("apple".equals("apple"));
System.out.println("apple".equals("Apple"));
System.out.println("apple".compareTo("banana"));
System.out.println("banana".compareTo("apple"));
System.out.println("apple".compareTo("apple"));
System.out.println("Zebra".compareTo("apple"));
true false -1 1 0 -7
The last result is negative because a capital Z is ordered before a lowercase a, so "Zebra" comes before "apple". Only the sign of a compareTo result is meaningful: the exact numbers above come from the way Java compares characters, and the exam asks only whether the result is below, equal to, or above zero. The == operator does not compare characters when applied to objects, and Lesson 2.6 explains why equals is the right choice.
### Strings never change
None of these methods changes the String it is called on. The result must be used or stored, or it is lost.
String s = "hello"; s.substring(1); System.out.println(s); s = s.substring(1); System.out.println(s);
hello ello
Split "Grace Hopper" into a first name and a last name by finding the space.
String full = "Grace Hopper";
int space = full.indexOf(" ");
String first = full.substring(0, space);
String last = full.substring(space + 1);
System.out.println(last + ", " + first);
System.out.println(space);
Hopper, Grace 5
| Piece | Expression | Value |
|---|---|---|
| index of the space | full.indexOf(" ") | 5 |
| first name | full.substring(0, 5) | Grace |
| last name | full.substring(6) | Hopper |
The first name ends before the space, so the end index is space, which is excluded. The last name begins after it, so the start index is space + 1.
What goes wrong, and when?
String s = "Java"; System.out.println(s.substring(1, 3)); System.out.println(s.substring(2, 6));
Exception in thread "main" java.lang.StringIndexOutOfBoundsException
The first line prints av; its indexes are inside 0 through 4. The second asks for an end index of 6, but the String has only 4 characters, so its largest legal end index is s.length(). The program compiles; the exception stops it at run time. Similar failures come from substring(-1) and from substring(s.indexOf("z")) when "z" is not found, because indexOf returns -1.
Which statement is true about each comparison?
String a = "cat";
String b = "catalog";
System.out.println(a.length() + " " + b.length());
System.out.println(b.substring(0, 3).equals(a));
System.out.println(a.compareTo(b) < 0);
System.out.println(b.compareTo(a) > 0);
System.out.println(b.indexOf("log"));
3 7 true true true 4
b.substring(0, 3) is "cat", which has the same characters as a. A shorter String that is a prefix of a longer one comes first, so a.compareTo(b) is negative and b.compareTo(a) is positive. The text log begins at index 4 of catalog.
These methods are tested heavily in multiple-choice tracing questions and in the String question of the free-response section. Practice a fixed routine: write the String with its indexes above it, then apply substring(from, to) by counting to - from characters. Look for the -1 that indexOf returns when the text is absent, the excluded end index, and the unassigned result of a String method. Using equals with an argument that is not a String is outside the course.
- What is printed?
String s = "programming"; System.out.println(s.length()); System.out.println(s.substring(3, 7)); System.out.println(s.indexOf("gram"));Show answer
11,gram, and3. The word has 11 characters. Indexes 3, 4, 5, and 6 areg,r,a,m, andgramstarts at index 3. - What is printed?
String s = "abcdef"; System.out.println(s.substring(2)); System.out.println(s.substring(0, s.length() - 1)); System.out.println(s.substring(s.length() - 2));
Show answer
cdef,abcde, andef.substring(2)runs to the end, the second drops the last character, and the third keeps the last two. - What does
"hello".indexOf("l")return, and what does"hello".indexOf("z")return?System.out.println("hello".indexOf("l")); System.out.println("hello".indexOf("z"));Show answer
2and-1.indexOfreports the first occurrence only, at index 2, and returns -1 when the text is not found. - Complete the statement so that
lastholds the last character ofwordas a String.String word = "science"; String last = word.substring(word.length() - 1); System.out.println(last);
Show answer
word.substring(word.length() - 1). The last index islength() - 1, andsubstring(from)runs to the end of the String. The formword.substring(word.length() - 1, word.length())is equivalent. - What is printed?
String s = "java"; s.substring(1, 3); System.out.println(s);
Show answer
java. The call returns"av", but the result is never stored, and Strings are immutable, sosis unchanged. - What happens when this code runs, and why?
String s = "tree"; System.out.println(s.substring(0, 5));
Show answer
A
StringIndexOutOfBoundsException. The String has length 4, so the end index cannot be larger than 4. The code compiles, and the failure happens at run time.