0

Can anyone explain why the o/p is like this for the code below:

public static void main(String[] args) {

            Integer i1=127;
            Integer i2=127;
            Integer i3=128;
            Integer i4=128;

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

O/p

true
false
Mukesh
  • 182
  • 1
  • 2
  • 10
  • use equals() to compare – Shasha Dec 14 '15 at 05:43
  • See this. It might help you http://stackoverflow.com/questions/14786014/why-2-objects-of-integer-class-in-java-cannot-be-equal – Joydeep Dec 14 '15 at 05:44
  • Thanks for the answer.That was helpful.Just checked the java.lang.Integer class and saw a inner class named IntegerCache which has the cache logic implemented. – Mukesh Dec 14 '15 at 05:56

1 Answers1

1

Values from -128 to 127 for int are cached for boxing. That's why the first comparison returns true.

http://www.mohawksoft.org/?q=node/70

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ramanlfc
  • 8,283
  • 1
  • 18
  • 24