Java
Programming
Integer Comparison
Coding Tips
Java Methods

How to compare two Integers in Java: equals vs Integer.compare

Codemia Knowledge Hub ·

For primitive int values, use == and the other comparison operators. For Integer objects, use .equals() for equality and Integer.compare() or .compareTo() for ordering. Never use == to compare Integer objects by value: it checks reference identity, and the Integer cache makes it look correct for small values before it fails on larger ones.

Comparing primitive int values

The operators ==, !=, <, >, <= and >= compare numeric values directly:

java
1int a = 1000;
2int b = 1000;
3
4System.out.println(a == b);  // true
5System.out.println(a < b);   // false
6System.out.println(a != b);  // false

No references are involved. If your variables are primitive int, stay with primitives: simpler, faster and no null surprises.

Comparing Integer objects

When you have Integer objects (from collections, database results, JSON parsing, or APIs that require objects), use these methods.

equals() for value equality

java
1Integer x = 200;
2Integer y = 200;
3
4System.out.println(x.equals(y));  // true

equals() compares the values inside both objects. x.equals(null) is safe and returns false, but calling equals on a null reference throws NullPointerException.

compareTo() for ordering

java
1Integer x = 100;
2Integer y = 200;
3
4System.out.println(x.compareTo(y));  // negative (x < y)
5System.out.println(y.compareTo(x));  // positive (y > x)
6System.out.println(x.compareTo(x));  // 0 (equal)

compareTo() returns a negative number, zero or a positive number. It implements Comparable<Integer> and is what sorted collections like TreeSet and TreeMap use.

Integer.compare() for static comparison

java
int result = Integer.compare(100, 200);  // negative

Integer.compare(int a, int b) takes primitive int parameters, avoiding autoboxing overhead. It is the preferred choice in comparators:

java
List<Integer> numbers = Arrays.asList(5, 2, 8, 1, 9);
numbers.sort(Integer::compare);
// Result: [1, 2, 5, 8, 9]

Why == fails with Integer objects

On objects, == checks whether both references point to the same object, not whether they hold the same value:

java
1Integer a = new Integer(5);
2Integer b = new Integer(5);
3
4System.out.println(a == b);      // false (different objects)
5System.out.println(a.equals(b)); // true  (same value)

The Integer cache trap

Java caches Integer objects for values from -128 to 127 by default. Autoboxing a value in that range returns the cached instance, so == appears to work for small values:

java
1Integer small1 = 100;   // cached
2Integer small2 = 100;   // same cached instance
3Integer large1 = 200;   // not cached, new object
4Integer large2 = 200;   // not cached, different new object
5
6System.out.println(small1 == small2);  // true  (same cached object)
7System.out.println(large1 == large2);  // false (different objects)

Code that passes tests with small values silently breaks once production data exceeds 127. The JVM flag -XX:AutoBoxCacheMax=N extends the cache range, but relying on cache behavior for correctness is wrong.

ExpressionPrimitive intInteger (cached range)Integer (outside cache)
a == bCompares valuestrue (same object)false (different objects)
a.equals(b)N/A (primitives)truetrue
Integer.compare(a, b)Compares values00
a.compareTo(b)N/A (primitives)00
Objects.equals(a, b)N/A (primitives)truetrue

Handling null safely

Unlike int, an Integer can be null, which matters when values come from database queries, API responses or optional fields:

java
1import java.util.Objects;
2
3Integer left = null;
4Integer right = 42;
5
6// Safe: Objects.equals handles null on either side
7System.out.println(Objects.equals(left, right));  // false
8System.out.println(Objects.equals(left, null));   // true
9System.out.println(Objects.equals(right, right)); // true
10
11// Unsafe: throws NullPointerException
12// left.equals(right);  // NPE
13// left.compareTo(right);  // NPE
14// left == right;  // false, but for wrong reason (reference check)

Objects.equals() is null-safe on both sides. Make it the default when either argument might be null.

For ordering with possible nulls, use Comparator.nullsFirst or Comparator.nullsLast:

java
1import java.util.Comparator;
2import java.util.Arrays;
3import java.util.List;
4
5List<Integer> values = Arrays.asList(3, null, 1, null, 2);
6values.sort(Comparator.nullsLast(Integer::compare));
7// Result: [1, 2, 3, null, null]

Unboxing to primitives

If null is impossible or already ruled out, unboxing to int simplifies comparison:

java
Integer boxed = 42;
int value = boxed;  // auto-unboxing
System.out.println(value == 42);  // true, primitive comparison

Unboxing a null reference throws NullPointerException:

java
Integer maybeNull = null;
int value = maybeNull;  // throws NullPointerException at runtime

A safe unboxing helper:

java
1public static int safeUnbox(Integer value, int defaultValue) {
2    return value != null ? value : defaultValue;
3}
4
5int timeout = safeUnbox(config.getTimeout(), 30);

Choosing the right comparison

ScenarioMethodWhy
Two primitive int values==, <, >Direct value comparison, no overhead
Two Integer objects, no nulls.equals()Value equality without cache dependency
Either might be nullObjects.equals()Null-safe on both sides
Ordering / sortingInteger.compare() or .compareTo()Returns negative/zero/positive
Sorting with nullsComparator.nullsFirst(Integer::compare)Explicit null placement policy
Comparator lambdaInteger::compareAvoids autoboxing, clean syntax

Bugs to watch for

  • == on Integer objects. The most common Java integer comparison bug. It compares references, and the cache hides the problem in tests with small numbers.
  • Calling .equals() on a possibly null reference. It throws NullPointerException. Use Objects.equals() when either side may be null.
  • Unboxing without a null check. int x = nullableInteger compiles but throws at runtime. Validate or supply a default first.
  • Mixing primitives and wrappers in conditions. someInteger == 5 auto-unboxes someInteger and throws if it is null. The compiler does not warn you.
  • Using Integer.valueOf() identity for value checks. Integer.valueOf(127) == Integer.valueOf(127) is true because valueOf is documented to always cache -128 to 127, but values outside that range may or may not be cached. Compare values with equals, not identity.

Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms