Sobes.tech
Senior

Integer i = 300, j = 300; System.out.println(i == j);

sobes.tech AI

Answer from AI

In this code, a comparison is made between two Integer objects using the == operator:

Integer i = 300, j = 300;
System.out.println(i == j); // false

Why is the result false? In Java, Integer objects are cached for values from -128 to 127. For values outside this range, new objects are created. Therefore, i and j with the value 300 are different objects, and == compares references, not values.

If the values were within the cache range, for example 100, then i == j would be true.

To compare the values of Integer objects, the .equals() method should be used:

System.out.println(i.equals(j)); // true