Check indexOf Against Zero
ID |
java.string_indexof_positive |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
code-style |
Description
Reports comparisons of indexOf() or lastIndexOf() against > 0 instead of >= 0 or != -1. Using > 0 misses the case where the substring is found at position zero.
Rationale
String.indexOf(s) returns 0 when s is found at the very beginning of the string. Comparing with > 0 silently excludes that match, which is almost never the intended behavior when checking for substring presence.
// Bad — misses match at position 0
if (text.indexOf("prefix") > 0) {
// never entered when text starts with "prefix"
}
Remediation
Use >= 0 or != -1 to check for substring presence, or use String.contains():
// Good
if (text.indexOf("prefix") >= 0) { ... }
if (text.indexOf("prefix") != -1) { ... }
if (text.contains("prefix")) { ... }