Search code examples
javareferenceintegercomparison-operators

Safety of comparison operators with Integer objects in Java


When is it safe to use comparison operators e.g. ==, >=, < in Java when using Integer objects and not primitive ints?

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html

I know == is dangerous with references, and you should use .equals instead, but what about the other operators? e.g.

int x = 7;
int y = 7;
Integer a = new Integer(7);
Integer b = new Integer(7);

System.out.println(x == y);
System.out.println(a == b);
System.out.println(a.equals(b));
System.out.println(a <= b);

prints

true
false // Why you should use .equals
true
true // Seemed dangerous but it worked?

Is it okay to use anything other than double equals (So >, <, >= and <= are safe?), or should I be using the .compareTo() method?


Solution

  • It is dangerous when the variable references null. The unboxing action will cause a NullPointerException.

    The <= and >= operators are different than ==. They can only be applied to numerical primitive types (and values), so reference equality is not an issue.