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:
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
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
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
Integer.compare(int a, int b) takes primitive int parameters, avoiding autoboxing overhead. It is the preferred choice in comparators:
Why == fails with Integer objects
On objects, == checks whether both references point to the same object, not whether they hold the 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:
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.
| Expression | Primitive int | Integer (cached range) | Integer (outside cache) |
a == b | Compares values | true (same object) | false (different objects) |
a.equals(b) | N/A (primitives) | true | true |
Integer.compare(a, b) | Compares values | 0 | 0 |
a.compareTo(b) | N/A (primitives) | 0 | 0 |
Objects.equals(a, b) | N/A (primitives) | true | true |
Handling null safely
Unlike int, an Integer can be null, which matters when values come from database queries, API responses or optional fields:
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:
Unboxing to primitives
If null is impossible or already ruled out, unboxing to int simplifies comparison:
Unboxing a null reference throws NullPointerException:
A safe unboxing helper:
Choosing the right comparison
| Scenario | Method | Why |
Two primitive int values | ==, <, > | Direct value comparison, no overhead |
Two Integer objects, no nulls | .equals() | Value equality without cache dependency |
| Either might be null | Objects.equals() | Null-safe on both sides |
| Ordering / sorting | Integer.compare() or .compareTo() | Returns negative/zero/positive |
| Sorting with nulls | Comparator.nullsFirst(Integer::compare) | Explicit null placement policy |
| Comparator lambda | Integer::compare | Avoids autoboxing, clean syntax |
Bugs to watch for
==onIntegerobjects. 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 throwsNullPointerException. UseObjects.equals()when either side may be null. - Unboxing without a null check.
int x = nullableIntegercompiles but throws at runtime. Validate or supply a default first. - Mixing primitives and wrappers in conditions.
someInteger == 5auto-unboxessomeIntegerand 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 becausevalueOfis documented to always cache -128 to 127, but values outside that range may or may not be cached. Compare values withequals, not identity.
Related reading
- How can I provide different database configurations with Spring Boot?
- How can I read a large text file line by line using Java?
- How can I read all files in a folder from Java?
- How can I read an AWS S3 File with Java?
- How can I read input from the console using the Scanner class in Java?
- How can I register a secondary servlet with Spring Boot?
- How can I remove a substring from a given String?
- How can I resolve the error The minCompileSdk 31 specified in a dependency's AAR metadata in native Java or Kotlin?
System design interview problems on this topic
- Design an API Rate Limiter: solution and walkthrough
- Design a Distributed Messaging System: solution and walkthrough
- Design an Online Payment Service: solution and walkthrough
- Design a Key Value Store: solution and walkthrough

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseData 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.