Two types of value assignment Analysis of the String class
1. String constant pool
2. String name = new String ("hello ");
3. String name = "hello ";
Structure of the analysis object in memory:
Constant pool -- used to store strings
Hello -- constant; name -- Variable
Every time a new object is created, an object is generated in the heap, And the pointer in the stack points to the heap. Hello, It is the value stored in heap memory. The "hello" string will be checked in the String constant pool, check whether the constant "hello" exists in the "String constant pool"-if not, the string "hello" will be saved to the "String constant pool.
String s1 = new String ("hello ");
String s2 = "hello"; // you can create a maximum of one String object. You may not need to create an object.
In summary, when s1 creates an object in the new string -- "hello" in the heap, it then saves "hello" to the String constant pool. (The String constant pool is in the heap memory)
Frequently Asked Questions during interviews:
String s1 = new String ("hello"); how many objects are created?
The answer is: two -- one is in the heap memory, and the other is in the constant pool.
1. Create a new value in the heap. 2. Store "hello" in the String constant pool. For the next time you use the same value, the new value will be found in the constant pool.
2. There is a benefit for the shorthand Method -- it will directly let s2 look for it in the constant pool to see if there are the same values, yes, direct to; no, A "hello" will be created in the constant pool, and s2 will point to "hello ".