The data segment of Java's "constant pool" appears to quickly and conveniently create some objects. If an object is required, it is extracted from it. If not, it is created. This eliminates the need to create multiple instances.
The differences between the objects in the constant pool and the basic types in the stack and the objects in the stack can be seen by the "=" operation.
Example 1:
String type
1) String a = "hello"; String B = "hello"; then a = B;
2) String a = new String ("hello"); String B = new String ("hello"); then! = B.
This is because 1) a points to the "hello" character string in the constant pool, and when B is instantiated, because "hello" exists in the constant pool, B is also directed to the object "hello ".
2) The Memory objects allocated in the heap space are "hello" and the pointer is given to a or B. Naturally, a and B are different.
Example 2:
Some basic types of packages
Byte, Short, Integer, Long, Character, Boolean. Here, Byte, Short, Integer, Long, and Character use the constant pool only when the value is less than or equal to 127.
Therefore:
1) Integer i1 = 127; Integer i2 = 127; then i1 = i2
2) Integer i1 = 128; Integer i2 = 128; then i1! = I2
Example 3:
= Of the object type is to compare the address of the object instance, rather than the value. The = comparison of the basic data type is the value.
Int I = 1; int j = 1; I and j are allocated in the stack, and their addresses are not the same, but their values are the same, so I = j.
However, if:
Public static final int I = 1;
Public static final int j = 1;
It is the 1 constant allocated in the constant pool, and all the references I and j point to it. Therefore, I = j.
In summary, the basic data types allocated in the stack are compared at =; the basic data types and object types allocated in the constant pool are compared addresses when = is used; the objects allocated in the heap are compared addresses when = is used. All constants are allocated in the constant pool.
Therefore, do not use the = operator of the object instance for Value Comparison. Instead, use equals.