What does the following code usually output? And why usually?

System.out.println(3 == 3);
 System.out.println(15000 == 15000);
 System.out.println((Integer)127 == (Integer)127);
 System.out.println((Integer)128 == (Integer)128);
1 answers

Output:

true,

true,

true,

false

With casting the values (Integer), a boxing of the primitive values to the object wrapper is done. Since this boxing has some performance impact, the JVM keeps a cache of the object wrappers in some range (for Integer the default range is [-127, 127]). This means that in the example (Integer)127 == (Integer)127 , the wrapper object for 127 is taken from the cache and that's why they are same by reference. In the example (Integer)128 == (Integer)128 , the value is false because the wrapper object is not cached (it is out of the default range), and the result is false because they are different by reference.

This is the usual case because the range is a JVM property that can be changed.

shilpigupta22 shilpigupta22 [Author] 4 months ago votes 0