In 51cto's self-testing question "self-testing questions that verify your Java proficiency (I)", the last question is about the memory space occupied by Java strings. The original question is as follows:
The answer to the question is a. 6 bytes. I don't think so.
String, as an object, is not simply a combination of character sets. It must also have memory overhead for the object. After investigation, according to the JVM memory structure, a formula for calculating the minimum number of bytes occupied by a string is provided.
- Minimum String memory usage (bytes) = 8 * (int) ((((chars number) * 2) + 45) / 8)
Not to mention the additional overhead of the object, how many bytes does it take for the characters "Learn Java? 6 bytes-no!
The characters in Java are saved in 16-bit Unicode. This is mentioned in the "primitive data types" chapter in the official book "The Java tutorial:
* CHAR: the char data type is a single 16-bit Unicode Character. It has a minimum value of '\ u0000' (or 0) and a maximum value of '\ uffff' (or 65,535 aggressive ). |
The five characters "Learn Java" should be 5*16 bit = 10 bytes, which occupies 10 bytes of memory space.
So how did the answer of the question come from 6 bytes? Try the following code:
- Public class test {
- Public static final void main (string [] ARGs ){
- System. Out. println ("Learn Java". getbytes (). Length );
- }
- }
Yes, I believe that users of Simplified Chinese Windows will get the answer 6 when running this code. Why does "Learn Java". getbytes () get 6 bytes? Let's take a look at what the getbytes () Documentation says.
Encodes this string into a sequence of bytes Using the platform's default charset, Storing the result into a new byte array. |
That is to say, getbytes () Will encode the string according to the default Character Set of the current system. The default Character Set of windows in simplified Chinese is GBK. The Chinese Character Set in GBK is 2 bytes, while ASCII occupies 1 byte. Therefore, "Learning Java" is 6 bytes.
If you do not know the default Character Set of the current platform/system, you can use this statement to look at it:
- System. Out. println (Java. NiO. charset. charset. defaultcharset (). tostring ());
Reference: http://jamesfancy.blog.51cto.com/2516291/665745