Sub topic 5
Length, char Values, and UTF-16 Indexes
A Java String holds text. Its length() method tells you how many positions Java uses to represent that text. Knowing these positions lets you read part of a string without reading the whole thing.
Counting and indexing
An index is a number that identifies a position in a string. Java starts counting indexes at zero. For the string "cat", the indexes are:
The string has a length of 3, but its last index is 2. For a nonempty string, the last index is always length() - 1.
The charAt() method reads the value at an index. It returns a char, a Java type that holds one 16-bit text unit. You can write a char value with single quotes, such as 'c'. A string uses double quotes, such as "cat".
Worked example
Save this program as StringIndexes.java:
class StringIndexes {
public static void main(String[] args) {
String word = "cat";
System.out.println("Length: " + word.length());
char first = word.charAt(0);
char last = word.charAt(word.length() - 1);
System.out.println("First: " + first);
System.out.println("Last: " + last);
for (int i = 0; i < word.length(); i++) {
System.out.println(i + ": " + word.charAt(i));
}
}
}Compile and run it:
javac StringIndexes.java
java StringIndexesThe output is:
Length: 3
First: c
Last: t
0: c
1: a
2: tThe loop starts at index 0. It continues while i is less than the length, so it stops after reading index 2.
Staying within bounds
A valid index is at least zero and less than the string's length. Calling word.charAt(3) in the example would cause a StringIndexOutOfBoundsException. That is an error caused by asking for a position outside the string.
An empty string, "", has length zero and no valid indexes. Check its length before trying to read its first or last value.
Why length is not always a character count
Java treats a string as a sequence of UTF-16 code units. UTF-16 is a way to represent text using 16-bit units. A char holds one such unit, and length() counts those units.
Many familiar characters, including the letters in "cat", use one unit each. Some symbols use two units, called a surrogate pair. For example:
class SymbolLength {
public static void main(String[] args) {
String text = "A\uD83D\uDE00";
System.out.println(text.length());
}
}Save this as SymbolLength.java, then compile and run it with javac SymbolLength.java and java SymbolLength. It prints 3. The text contains A followed by one emoji, but the emoji uses two UTF-16 units.
| Index | UTF-16 unit |
|---|---|
| 0 | `A` |
| 1 | First unit of the emoji |
| 2 | Second unit of the emoji |
So charAt(1) returns only the first unit of the emoji, not the whole symbol. A string's length is useful for safe indexing, but it is not always the number of visible characters.
Exercise
For String word = "lamp", what are word.length() and word.charAt(3)? Is index 4 valid?
Show answer
The length is 4, and word.charAt(3) is 'p'. Index 4 is not valid; the indexes run from 0 through 3.