Java Language Getting the length of a String


In order to get the length of a String object, call the length() method on it. The length is equal to the number of UTF-16 code units (chars) in the string.

String str = "Hello, World!";
System.out.println(str.length()); // Prints out 13

Live Demo on Ideone

A char in a String is UTF-16 value. Unicode codepoints whose values are ≥ 0x1000 (for example, most emojis) use two char positions. To count the number of Unicode codepoints in a String, regardless of whether each codepoint fits in a UTF-16 char value, you can use the codePointCount method:

int length = str.codePointCount(0, str.length());

You can also use a Stream of codepoints, as of Java 8:

int length = str.codePoints().count();