3

The following string st contains just 18 characters but when I print its length it shows 36 its twice.

String st = "";
System.out.println(st.length());

Note: The string contains symbols which I am going to use in my chat application, the length maybe vary due to 16bit and 8bit characters but I am blurry about it.

Muhammad
  • 6,725
  • 5
  • 47
  • 54

1 Answers1

6

According to the JavaDocs: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#length()

Returns the length of this string. 
The length is equal to the number of Unicode code units in the string.

If you have Unicode characters that require multiple bytes then length() returns the total amount of bytes and not the actual number of characters.

Mike Laren
  • 8,028
  • 17
  • 51
  • 70
  • 2
    Also, if you're interested in finding the visual length, you can use `str.codePointCount(0, str.length())` - see [this related question](http://stackoverflow.com/questions/6828076/how-to-correctly-compute-the-length-of-a-string-in-java) – Krease Oct 18 '14 at 04:31
  • 3
    It is not the length in bytes, but the number of code points required to form the character. Java uses utf16 which can't encode all characters, so it uses surrogate pairs for some of the characters. – Mark Rotteveel Oct 18 '14 at 05:00