String.indexOf() With Single-Character String
ID |
java.string_indexof_single_char |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Efficiency |
Language |
Java |
Tags |
best-practice, efficiency |
Description
Reports calls to String.indexOf() or String.lastIndexOf() where the argument is a single-character String literal (e.g., indexOf("x")). The char overload indexOf('x') should be preferred for better performance.
Rationale
When indexOf(String) is called with a single-character string, the JVM must perform full substring matching logic, including boundary checks and character-by-character comparison through the String API. The indexOf(int) overload operates directly on the character array with a simple loop, avoiding the overhead of String matching entirely. In code that searches strings frequently, this adds up.
// Bad -- single-char string literal
int pos = text.indexOf("/");
int last = text.lastIndexOf(".");
Remediation
Replace the single-character String literal with the corresponding char literal.
// Good -- char literal
int pos = text.indexOf('/');
int last = text.lastIndexOf('.');