Is it safe to compare two `Integer` values with `==` in Java?

No, it's not the right way to compare the Integer objects. You should use Integer.equals() or Integer.compareTo() method.

By default JVM will cache the Integer values from [-128, 127] range (see java.lang.Integer.IntegerCache.high property) but other values won't be cached:

Integer x = 5000;
Integer y = 5000;
System.out.println(x == y); // false

Unboxing to int or calling Integer.intValue() will create an int primitive that can be safely compared with == operator. However unboxing a null will result in NullPointerException.

Tags:

Java