Literal constants in Java (distinguished from the well-known constants created by final) are usually stored in a constant pool, which can be understood as a heap-like area of memory. However, a constant pool has an attribute that if the constant is already present in the constant pool, it will not open memory again for that constant .
Or see a program:
Packagereverse; Public classReverse { Public Static voidMain (string[] args) {String S1= "Zhanghanqing"; String S2= "Zhanghanqing"; String S3=NewString ("Zhanghanqing"); System.out.println ("" + (s1==S2)); System.out.println ("" + (s1==S3)); System.out.println ("-----------------------"); Integer I=integer.valueof (5); Integer J=integer.valueof (5); Integer Q=5; System.out.println ("" + (i==J)); System.out.println ("" + (j==Q)); System.out.println ("-----------------------"); Integer k=integer.valueof (128); Integer g=integer.valueof (128); System.out.println ("" + (k==g)); System.out.println ("-----------------------"); Double D=12.5; Double e=12.5; System.out.println ("" + (d==e)); }}
The output is:
The string objects referenced by S1 are literal constants that are stored in a constant pool,
The string object referenced by S2 is also a literal constant, and the constant "Zhanghanqing" appears in the constant pool, so Java does not open up new memory for the object referenced by S2, but instead allows S2 to refer directly to the previously existing "Zhanghanqing"
In-Memory impersonation:
So S1==s2 is true;
S3 is created with new, and the memory of the object should be in the heap;
So S1==s3 is false.
In addition to the literal constants of the string class, a constant pool is used, and the wrapper class for the Java base type also uses a constant pool, including Byte,short,integer,long,character,boolean;
So i==j==q is True
It is important to note that the wrapper class for the 5 integer types also only uses the object pool when the corresponding value is less than or equal to 127, that is, the object is not responsible for creating and managing objects greater than 127 of these classes Byte,short,integer,long,character
So K==g is false.
In addition, double and float do not implement constant pool technology.
So D==e is false.
Java literal constants and constant pools