CKTIS / Java
Integer.equals: same wrapper type and value, not object identity
`Integer.equals` checks the argument’s wrapper type and stored `int` value. With two `Integer` references, `==` checks object identity instead.
Version: Java SE 21
Syntax
public boolean equals(Object obj)
// Instance call: a.equals(obj), where a is a non-null IntegerInteger.equals(Object obj) is an instance method of java.lang.Integer that overrides Object.equals(Object). It returns true only for an Integer holding the same int value; the two references need not point to the same object. If a holds 42, a.equals(42) is true because 42 is boxed to an Integer. But a.equals(42L) is false because 42L is boxed to a Long; the method does not compare numbers across wrapper types.
If a and b both have type Integer, a == b checks whether they refer to the same object or are both null. Integer.valueOf(int) caches values from -128 through 127 and may cache others, so do not use == to compare the values of two Integer objects. In a == 42L, by contrast, 42L is a primitive long, so a is unboxed and the comparison is numeric. Unboxing null throws NullPointerException.
With a non-null a, a.equals(null) returns false. If a itself is null, calling a.equals(b) throws NullPointerException. If either of two Integer references may be null, use Objects.equals(a, b): it returns true when both are null, false when exactly one is null, and applies Integer.equals when neither is null.
Examples
import java.util.Objects;
public class Main {
public static void main(String[] args) {
Integer a = Integer.valueOf(42);
Integer b = Integer.valueOf(42);
System.out.println(a.equals(b));
System.out.println(a == b);
System.out.println(a.equals(42));
System.out.println(a.equals(42L));
System.out.println(a == 42L);
System.out.println(a.equals(null));
System.out.println(Objects.equals(null, null));
}
}Result
true true true false true false true
The first two results are both `true` for different reasons: the values match, and `Integer.valueOf(42)` reuses the cached object. Compare `a.equals(42L)` with `a == 42L`: the former checks the wrapper type; the latter compares numbers.
Related lessons
- Java · Lesson 4 · Advanced · Version: 2
Sources
- Java SE 21 API — Integer.equals(Object)
- Java SE 21 API — Integer.valueOf(int)
- Java SE 21 API — Objects.equals(Object, Object)
- Java Language Specification, Java SE 21 — §15.21 Equality Operators
- Java Language Specification, Java SE 21 — §5.1.7 Boxing Conversion
- Java Language Specification, Java SE 21 — §5.1.8 Unboxing Conversion
- Java Language Specification, Java SE 21 — §15.12.4.4 Locate Method to Invoke