Literals First In Comparison

ID

java.literals_first_comparison

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

reliability

Description

Reports variable.equals("literal") and variable.equalsIgnoreCase("literal") where the literal is on the right-hand side. The literal-on-the-left form ("literal".equals(variable)) is null-safe — a null receiver throws NPE in the former; in the latter it just returns false.

Rationale

String literals are never null. Putting the literal on the left turns the equals call into a null-tolerant comparison:

  • variable.equals("literal") — if variable is null, throws NullPointerException.

  • "literal".equals(variable) — if variable is null, returns false.

The flipped form expresses "is variable equal to this known value?" without an implicit assumption about the variable’s nullness, and removes the need for a separate null check at the call site.

// Bad — NPE if s == null
if (s.equals("yes")) { ... }

// Good — false if s == null
if ("yes".equals(s)) { ... }

Remediation

Flip the operands: put the known literal on the left of equals / equalsIgnoreCase.