Object Equality Use Equals

ID

java.object_equality_use_equals

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

CWE:480, reliability, suspicious-comparison

Description

Reports uses of == or != to compare reference-type objects instead of equals(). The identity operators test whether two references point to the same object in memory, not whether they are logically equal, leading to subtle bugs.

Rationale

The == operator checks reference identity, not logical equality. Two distinct objects that represent the same value will compare as not equal:

Date a = new Date(0L);
Date b = new Date(0L);
if (a == b) {             // false: different objects
    process();
}

This mistake is common when working with collections, DTOs, entities, and value objects.

The following comparisons are intentionally not flagged:

  • null checks (a == null, a != null)

  • Enum comparisons (status == Status.ACTIVE) — enums are singletons, so == is correct

  • String comparisons — handled by the companion rule java.string_equality_use_equals

  • Primitive-type comparisons (int, long, etc.) — value types

Remediation

Use equals() (or Objects.equals() for null-safe comparison) for content equality:

Date a = new Date(0L);
Date b = new Date(0L);
if (a.equals(b)) {        // true: same value
    process();
}