Sub topic 5
Length, char Values, and UTF-16 Indexes
A Java String is a value that holds text. Often, you need to know how long that text is or look at one part of it. For example, you might check whether a name has any text before reading its first character.
Java measures a string using UTF-16 code units. A code unit is a small piece of text data. A char is a Java primitive type that holds one UTF-16 code unit. For many familiar letters, one char represents one letter. But that is not true for all text.
Finding the length
The length() method gives the number of UTF-16 code units in a string. A method is an action you can ask a value to perform.
For text made of simple English letters, this count is also the number of letters:
"Java".length()is4."Hi".length()is2."".length()is0.
Spaces and line breaks count too. For example, "Hi " has a length of 3: its last code unit is a space. The string "Hi\n" also has a length of 3. The escape sequence \n represents one line break.
Call length() with parentheses because it is a method. This differs from an array, which uses the length field without parentheses.
Reading a char by index
An index is a number that identifies a position in a string. Java starts counting at 0, not 1.
Here are the indexes in "Java":
| Index | `char` value |
|---|---|
| `0` | `J` |
| `1` | `a` |
| `2` | `v` |
| `3` | `a` |
The charAt() method returns the char at a given index. For example, "Java".charAt(2) returns 'v'.
A char and a String are different types. Single quotes write a char value, such as 'v'. Double quotes write a String value, such as "v", even when it contains only one code unit.
Worked example
Save this program as ReadChars.java, then compile and run it:
class ReadChars {
public static void main(String[] args) {
String word = "Java";
System.out.println("Length: " + word.length());
char first = word.charAt(0);
System.out.println("First: " + first);
for (int i = 0; i < word.length(); i++) {
System.out.println(i + ": " + word.charAt(i));
}
if (word.length() > 0) {
char last = word.charAt(word.length() - 1);
System.out.println("Last: " + last);
}
}
}The program prints:
| Output line | Meaning |
|---|---|
| `Length: 4` | The string has four code units. |
| `First: J` | Index `0` holds `J`. |
| `0: J` | The loop reads index `0`. |
| `1: a` | The loop reads index `1`. |
| `2: v` | The loop reads index `2`. |
| `3: a` | The loop reads index `3`. |
| `Last: a` | The last index is `4 - 1`, or `3`. |
The loop starts at index 0. Its condition, i < word.length(), stops the loop before i reaches 4. That matters because 4 is the length, not a valid index.
The if statement checks that the string is not empty before reading its last char. An empty string has length 0 and has no valid indexes.
Staying within bounds
For a string with a length greater than zero:
- The first valid index is
0. - The last valid index is
length() - 1. - The index
length()is not valid.
An index is out of bounds when it is outside the valid range. If you call charAt() with such an index, Java throws a StringIndexOutOfBoundsException. An exception is a signal that an operation could not complete normally.
For "Java", both charAt(-1) and charAt(4) are out of bounds. For the empty string "", even charAt(0) is out of bounds.
A null reference is not an empty string. It does not refer to a string at all, so calling length() or charAt() on it causes a NullPointerException.
Why length is not always a character count
Unicode is a system for representing text from many writing systems, as well as symbols. UTF-16 is a way to represent Unicode text using 16-bit code units. Java’s String indexes and lengths are defined in terms of those code units.
Many common characters fit in one code unit. Some need two. When two code units represent one such character, they form a surrogate pair. Each half of the pair is a separate char.
Consider a string containing A followed by the smiling face 😀. The string has two visible symbols but three UTF-16 code units:
| Index | Code unit | Role |
|---|---|---|
| `0` | `0041` | The letter `A` |
| `1` | `D83D` | First half of the surrogate pair |
| `2` | `DE00` | Second half of the surrogate pair |
The values in this table are written in hexadecimal, a number system that uses digits 0 through 9 and letters A through F.
Worked example with a surrogate pair
Save this program as CountUnits.java, then compile and run it:
class CountUnits {
public static void main(String[] args) {
String text = "A\uD83D\uDE00";
System.out.println("Length: " + text.length());
for (int i = 0; i < text.length(); i++) {
System.out.printf(
"Index %d: %04X%n", i, (int) text.charAt(i)
);
}
}
}The \u sequences put the two code units of the smiling face into the string. The program prints:
| Output line | Meaning |
|---|---|
| `Length: 3` | The string has three UTF-16 code units. |
| `Index 0: 0041` | The code unit for `A`. |
| `Index 1: D83D` | The first half of the pair. |
| `Index 2: DE00` | The second half of the pair. |
The cast (int) converts each char to a number. The printf method then prints that number in hexadecimal; %04X requests at least four hexadecimal digits.
Notice that charAt(1) returns only the first half of the pair. It does not return the whole smiling face. A char can hold one code unit, but some characters need two.
Visible text can be more complex
Even counting Unicode characters is not always the same as counting what a person sees. For example, e followed by a separate accent mark can appear as one accented letter. The string "e\u0301" has two UTF-16 code units, even though it can look like one letter.
So keep these questions separate:
length()answers: “How many UTF-16 code units are in this string?”charAt(i)answers: “Which code unit is at indexi?”- Neither method alone answers: “How many visible characters does a person see?”
For simple English text, the answers often match. For other text, choose an approach based on what you need to count or read. Unicode characters and text boundaries receive further attention later in the tutorial.
Practice
Exercise
What are the length, first valid index, and last valid index of "Cat"?
Show answer
The length is 3. The first valid index is 0, and the last valid index is 2.
Exercise
Why does "Cat".charAt(3) fail?
Show answer
The valid indexes are 0, 1, and 2. Index 3 equals the length and is out of bounds.
Exercise
A string contains "A" followed by a smiling face represented by a surrogate pair. What does length() return, and why?
Show answer
It returns 3: one UTF-16 code unit for A and two for the smiling face.