I saw such a question in the forum today.
Int K = 100;
Integer int1 = integer. valueof (k );
Integer int2 = integer. valueof (k );
System. Out. println ("A." + (int1 = int2); // true
K = 200;
Integer int3 = K;
Integer int4 = K;
System. Out. println ("B." + (int3 = int4); // false
Char c = 'a ';
Character char1 = C;
Character char2 = C;
System. Out. println ("C." + (char1 = char2); // true
C = 'status ';
Character char3 = C;
Character char4 = C;
System. Out. println ("D." + (char3 = char4); // false
What is the result? I wrote all the answers below.
For integer int1 = integer. valueof (k );
We all know that it is the automatic binning function added by jdk1.5, that is, automatic conversion of the original class and its encapsulation class.
However, the later int1 = int2 returns true, and the same method int3 = int4 returns false, which makes it hard to figure out.
Finally, I understood it only after reading the JDK source code.
Source code of valueof:
Public static integer valueof (int I )...{
Final int offset = 128;
If (I> =-128 & I <= 127)... {// must Cache
Return integercache. cache [I + offset];
}
Return new INTEGER (I );
}
It processes the size of byte (-128-127), which is obtained from the 256 integer cache initialized by integercache.
In this way, only one object is of course true, and the following 200 is out of the range and a new INTEGER (I) is used to generate a new object, and the return value is false.