0
    Integer a = 127;
    Integer b = 127;
    System.out.println(a == b);

The result is true, but:

    Integer a = 128;
    Integer b = 128;
    System.out.println(a == b);

The result is false. Why?

Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
yelliver
  • 5,648
  • 5
  • 34
  • 65

1 Answers1

6

You shouldn't compare objects this way in Java. When you compare them like a == b, you compare references but not values.

You should use equals method.

Integer a = 127;
Integer b = 127;

System.out.println(a.equals(b));

If you ask why is this happening for integers under 128: Java uses pools for small values. So, all integers under 128 do not create new instances but use "pooled", cached one.

This question is actually has been asked on SO. Read these articles:

Community
  • 1
  • 1
Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
  • You said Java uses pools for small values but why I cannot compare 2 small Float? (Float a = 1f; Float b = 1f) – yelliver Sep 18 '15 at 06:25