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?
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?
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: