Hang the interviewer and talk about: the size of the String object in Java? (the most complete in history)

Here is a common Java interview question:

Chat: The size of the String object in Java?

First, look at the space occupied by an empty String

The current memory size is under the condition that the compressed pointer is turned on by default

  • object head 12
  • char[] array reference 4
  • int type hash data size 4
  • loss due to the next object alignment alignment padding 4
    summary: 24

Again, let's look at the member variables in the String class.

/** The value is used for character storage. */ 
private final char value[];

/** Cache the hash code for the string */ 
private int hash; // Default to 0

/** use serialVersionUID from JDK 1.0.2 for interoperability */ 
private static final long serialVersionUID = -6849794470754667710L;

Space occupied by a non-empty String

The current memory size is under the condition that the compressed pointer is turned on by default

  • object head 12
  • char[] array reference 4
  • int type hash data size 4
  • loss due to the next object alignment alignment padding 4
    summary: 24

Recommended reading:

Guess you like

Origin blog.csdn.net/crazymakercircle/article/details/128258374