String Comparison for Single Character

ID

java.string_compare_for_single_char

Severity

info

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Efficiency

Language

Java

Tags

best-practice, efficiency

Description

Reports calls to String.equals("x") or String.equalsIgnoreCase("x") where the argument is a single-character String literal. Comparing against a single character via charAt(0) with a length check is more efficient, as it avoids the overhead of String object comparison.

Rationale

When comparing a String to a single-character literal, equals() must check the argument’s class, its length, and then compare each character. A direct charAt(0) == 'x' comparison (guarded by a length() == 1 check) reduces this to two integer comparisons with no object overhead.

// Bad -- String.equals() for single char
if (s.equals("x")) { ... }
if (s.equalsIgnoreCase("A")) { ... }

Remediation

Use charAt() with a length check for equals, or consider equalsIgnoreCase alternatives.

// Good -- direct char comparison
if (s.length() == 1 && s.charAt(0) == 'x') { ... }