java
runtime_error
ai_generated
true
java.lang.StringIndexOutOfBoundsException: String index out of range: ...
ID: java/stringindexoutofboundsexception
92%Fix Rate
87%Confidence
1Evidence
2023-04-05First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| Java 8 | active | — | — | — |
| Java 11 | active | — | — | — |
| Java 17 | active | — | — | — |
| Java 21 | active | — | — | — |
Root Cause
Accessing a character in a string at an index that is negative or greater than or equal to the string length.
generic中文
在字符串中访问索引为负数或大于等于字符串长度的字符。
Official Documentation
https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/StringIndexOutOfBoundsException.htmlWorkarounds
-
95% success Always check string length before accessing: 'if (index >= 0 && index < str.length()) { char c = str.charAt(index); }'
Always check string length before accessing: 'if (index >= 0 && index < str.length()) { char c = str.charAt(index); }' -
90% success Use safe substring with bounds clamping: 'int safeEnd = Math.min(end, str.length()); String sub = str.substring(start, safeEnd);'
Use safe substring with bounds clamping: 'int safeEnd = Math.min(end, str.length()); String sub = str.substring(start, safeEnd);'
中文步骤
Always check string length before accessing: 'if (index >= 0 && index < str.length()) { char c = str.charAt(index); }'Use safe substring with bounds clamping: 'int safeEnd = Math.min(end, str.length()); String sub = str.substring(start, safeEnd);'
Dead Ends
Common approaches that don't work:
-
90% fail
Using String.charAt() without checking length first leads to this exception when the string is shorter than expected.
-
85% fail
Assuming substring(start, end) works with end > length will throw this exception.