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

Feedback about page:

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


Strings:
* Getting the length of a String

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap