0
public static void main(String[] args) throws FileNotFoundException, IOException {
    Integer a = 120;
    Integer b = 120;
    Integer c = 130;
    Integer d = 130;
    System.out.println(a==b); //true
    System.out.println(c==d); //false
}

This behavior confused me. Can anyone explain it?

  • Don't use the box'ed object, change `Integer` to `int` and you'll see what you expect – Kevin DiTraglia Aug 09 '14 at 19:20
  • @DmitryFucintv The behaviour of both `==` vs `equals` in Java and the integer cache have both been explained many times in many answers. That's most likely why you are getting a couple of downvotes. – Tim B Aug 09 '14 at 19:27

2 Answers2

3

Java has an IntegerCache that caches all values stored between -128 and 127.

120 < 127 so it is in the cache but 130 > 127 so it isn't in the cache and Java's AutoBoxing will create a new Integer instance for that

David Xu
  • 5,555
  • 3
  • 28
  • 50
0

David Xu is correct, if you change your test to:

Integer a = new Integer(120);
Integer b = new Integer(120);
Integer c = new Integer(130);
Integer d = new Integer(130);
System.out.println(a==b); //false
System.out.println(c==d); //false

You will get double false because the new keyword creates a new Integer object each time and hence bypasses the cache.

Tim B
  • 40,716
  • 16
  • 83
  • 128