Getting the length of a String

suggest change

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 a UTF-16 code unit. Code points above U+FFFF, including most emoji, use two char positions. U+1000 is still one unit. To count Unicode code points, use codePointCount:

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

As of Java 8 you can also stream the code points. count() returns a long, not an int:

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents