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.
The receiver must resolve to java.lang.String. startsWith and endsWith are common method names: java.nio.file.Path declares both over whole path elements, where no charAt equivalent exists, and AssertJ’s assertThat(url).endsWith("/") reads exactly like the flawed call while being the assertion itself. A receiver the engine cannot resolve is not reported.
The argument is read off the AST as a string literal, so escapes count as the single characters they are: s.startsWith("\n") is reported.
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') { ... }