0

I think that the output should be (true true). Sorry for my english

  public class A{
     public static void main(String[] args)  {
       Integer i1 = 128;
       Integer i2 = 128;
       System.out.println(i1 == i2);

       Integer i3 = 127;
       Integer i4 = 127;
       System.out.println(i3 == i4);
     }
    }
Alex.M
  • 11
  • 2

2 Answers2

2

There is a cache of Integer instances for a range of values (at least -128–127), that is used when implicitly converting an int to an Integer.

In this case, 128 is not in the cache, and so each Integer object representing that value is new and distinct.

The value 127, on the other hand, is guaranteed to be in the cache, and so the same instance of Integer is obtained repeatedly.

erickson
  • 265,237
  • 58
  • 395
  • 493
0

Integer, as opposed to the primitive int, is an object. Your comparison is comparing two objects of type Integer. I'm kind of surprised you get "false true". If you instead try:

System.out.println(i1.intValue() == i2.intValue());
System.out.println(i3.intValue() == i4.intValue());

you should get the expected result.

ZSButcher
  • 60
  • 1
  • 10