Java Language Strings Getting the length of a String

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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();


Got any Java Language Question?