Why Java does not see that Integers are equal?

Check out this article: Boxed values and equality

When comparing wrapper types such as Integers, Longs or Booleans using == or !=, you're comparing them as references, not as values.

If two variables point at different objects, they will not == each other, even if the objects represent the same value.

Example: Comparing different Integer objects using == and !=.

Integer i = new Integer(10);
Integer j = new Integer(10);
System.out.println(i == j); // false
System.out.println(i != j); // true

The solution is to compare the values using .equals()

Example: Compare objects using .equals(…)

Integer i = new Integer(10);
Integer j = new Integer(10);
System.out.println(i.equals(j)); // true

…or to unbox the operands explicitly.

Example: Force unboxing by casting:

Integer i = new Integer(10);
Integer j = new Integer(10);
System.out.println((int) i == (int) j); // true

References / further reading

  • Java: Boxed values and equality
  • Java: Primitives vs Objects and References
  • Java: Wrapper Types
  • Java: Autoboxing and unboxing

If they were simple int types, it would work.

For Integer use .intValue() or compareTo(Object other) or equals(Object other) in your comparison.


In java numeric values within range of -128 to 127 are cached so if you try to compare

Integer i=12 ;
Integer j=12 ; // j is pointing to same object as i do.
if(i==j)
   print "true";

this would work, but if you try with numbers out of the above give range they need to be compared with equals method for value comparison because "==" will check if both are same object not same value.


There are two types to distinguish here:

  • int, the primitive integer type which you use most of the time, but is not an object type
  • Integer, an object wrapper around an int which can be used to use integers in APIs that require objects

when you try to compare two objects (and an Integer is an object, not a variable) the result will always be that they're not equal,

in your case you should compare fields of the objects (in this case intValue)

try declaring int variables instead of Integer objects, it will help