Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Long.equals: value equality for Long objects

`Long.equals` compares the values stored in `Long` objects. Unlike `==` between two references, it does not test object identity.

Version: Java SE 21

Syntax

public boolean equals(Object obj)

// Instance call, where value is a non-null java.lang.Long:
boolean same = value.equals(other);

Long.equals is an instance method of java.lang.Long that overrides Object.equals(Object). It returns true only when the argument is a Long holding the same long value. A different value, a different object type, or a null argument gives false. The two references need not point to the same object.

The parameter type is Object. If a is a Long holding 42, a.equals(42L) returns true because 42L is boxed to Long. In contrast, a.equals(42) returns false because 42 is boxed to Integer. The method does not convert values between wrapper types.

With two Long operands, == compares references, not the stored numbers. Long.valueOf(long) always reuses cached objects for values from -128 through 127 and may do so for other values, so do not use == to compare the values of two Long objects. With two primitive long operands, == compares numbers. With one Long and one primitive long, Java unboxes the Long before comparing; unboxing null throws NullPointerException.

a.equals(null) returns false if a is non-null. If a itself is null, a.equals(b) throws NullPointerException. When either of two Long references may be null, use Objects.equals(a, b): it returns true for two nulls, false for exactly one null, and otherwise applies Long.equals.

Examples

import java.util.Objects;

public class LongEquality {
    public static void main(String[] args) {
        Long a = Long.valueOf(42L);
        Long b = Long.valueOf(42L);
        Long missing = null;

        System.out.println(a.equals(b));
        System.out.println(a.equals(43L));
        System.out.println(a.equals(42));
        System.out.println(a.equals(null));
        System.out.println(a == b);
        System.out.println(a == 42L);
        System.out.println(Objects.equals(a, missing));
        System.out.println(Objects.equals(missing, null));
    }
}

Result

true
false
false
false
true
true
false
true

The first four lines show the results for the same `Long` value, a different value, an `Integer` argument, and a `null` argument. Both `==` comparisons print `true`, but for different reasons: the first compares references to the same cached object, while the second compares values after unboxing. The last two lines show `Objects.equals` with one and two `null` arguments.

Related lessons

  • Java · Lesson 4 · Advanced · Version: 2

Sources