Principal
public class Main { public static void main(String[] args) { Integer a = 127; Integer b = 127; Integer c = 128; Integer d = 128; System.out.println(a == b); System.out.println(c == d); } }
sobes.tech AI
Answer from AI
In Java, when comparing objects of type Integer using ==, references are compared, not values. However, for values in the range from -128 to 127, object caching (Integer Cache) is used.
In your example:
aandbare equal to 127, both referencing the same cached object, soa == bwill betrue.canddare equal to 128, which is outside the cache range, so different objects are created, andc == dwill befalse.
To compare values, you should use the .equals() method:
System.out.println(a.equals(b)); // true
System.out.println(c.equals(d)); // true