register, stack, heap, other

In terms of speed, there is the following relationship: 

    Register > Stack > Heap > Other

Here we mainly care about stack, heap and constant pool. Objects in stack and constant pool can be shared, but objects in heap cannot be shared. The size and life cycle of the data in the stack can be determined. When there is no reference to the data, the data will disappear. The objects in the heap are collected by the garbage collector, so the size and life cycle do not need to be determined, which has great flexibility.

    For strings: the references to their objects are stored in the stack. If they are created at compile time (defined directly with double quotes), they are stored in the constant pool. If they are created at runtime (new), they can be determined. are stored in the heap. For strings whose equals are equal, there is always only one copy in the constant pool and multiple copies in the heap.

Such as the following code:

Java code  

String s1 = "china";  

String s2 = "china";  

String s3 = "china";  

String ss1 = new String("china");  

String ss2 = new String("china");  

String ss3 = new String("china");  

 

When a string is generated by new (assuming "china"), it will first go to the constant pool to find out whether there is already a "china" object, if not, create a string object in the constant pool, and then store it in the heap. Create a copy of this "china" object in the constant pool.

This is the interview question:

 String s = new String("xyz"); How many objects are produced? One or two, or two if "xyz" wasn't originally in the constant pool.


Reprinted from: https://blog.csdn.net/u012031380/article/details/54981472

 

 

对于基础类型的变量和常量:变量和引用存储在栈中,常量存储在常量池中。

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324489122&siteId=291194637