Explain what does this program print? Explain the code functionality.
Integer i = 260;
Integer j = 260;
if(i == j) {
System.out.println(true);
else {
System.out.println(false);
}
This program will print false
. Let’s explain why:
In Java, for objects of the Integer
class (and other wrapper classes like Long
, Short
, etc.), Java maintains a pool of objects for certain integer values within a specific range (typically between -128 and 127). This range is called the “cached” or “interned” range.
When you create an Integer
object using autoboxing or by directly assigning an integer value within this range, Java will reuse an existing object from the pool if one exists. This means that if you create two Integer
objects with the same value within this range, they will actually reference the same object in memory.
However, for values outside this cached range, Java will create a new Integer
object for each value, even if they have the same numerical value. This means that two Integer
objects with values outside the cached range will not reference the same object in memory.
In the above-mentioned code:
i
andj
are both assigned the value260
.- Since
260
is outside the range of-128
to127
, Java will create newInteger
objects for bothi
andj
, rather than reusing cached objects. - Therefore,
i
andj
will reference differentInteger
objects, even though they have the same value.
As a result, when comparing i == j
, the condition will be evaluated to false
because i
and j
refer to different object instances.
So, the program will print false
.