Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (4k points)
In Java, if I have a String x, how can I calculate the number of bytes in that string?

1 Answer

0 votes
by (46k points)

The pedantic answer (though not necessarily the most useful one, depending on what you want to do with the result) is:

string.length() * 2

Java strings are physically stored in UTF-16BE encoding, which uses 2 bytes per code unit, and String.length() measures the length in UTF-16 code units, so this is equivalent to:

final byte[] utf16Bytes= string.getBytes("UTF-16BE");

System.out.println(utf16Bytes.length);

And this will tell you the size of the internal char array, in bytes.

Note: "UTF-16" will give a different result from "UTF-16BE" as the former encoding will insert a BOM, adding 2 bytes to the length of the array.

Browse Categories

...