Use charAt() for single-character prefix/suffix test
ID |
java.string_charat_for_single_char_test |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Efficiency |
Language |
Java |
Tags |
code-style, efficiency |
Description
Reports calls to String.startsWith("x") or String.endsWith("x") where the argument is a single-character string literal. A charAt() comparison is more efficient.
Rationale
String.startsWith(String) and String.endsWith(String) perform region matching that is unnecessary when the prefix or suffix is a single character. A direct charAt(0) == 'x' (or charAt(length()-1) == 'x') comparison avoids the method call overhead and temporary string allocation.
// Bad - unnecessary overhead for single char
if (s.startsWith("x")) { ... }
if (s.endsWith("y")) { ... }
Remediation
Use charAt() for single-character comparisons.
// Good - direct char comparison
if (s.charAt(0) == 'x') { ... }
if (s.charAt(s.length() - 1) == 'y') { ... }