java
runtime_error
ai_generated
true
java.lang.StringIndexOutOfBoundsException: String index out of range: 10
ID: java/string-index-out-of-bounds-exception
88%Fix Rate
83%Confidence
1Evidence
2023-12-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| Java 8 | active | — | — | — |
| Java 11 | active | — | — | — |
| Java 17 | active | — | — | — |
| Java 21 | active | — | — | — |
Root Cause
An attempt to access a character in a String using an index that is negative or greater than or equal to the string length, often due to off-by-one errors or malformed input.
generic中文
尝试使用负数或大于等于字符串长度的索引访问字符串中的字符,通常由差一错误或格式错误的输入引起。
Official Documentation
https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/StringIndexOutOfBoundsException.htmlWorkarounds
-
95% success Check the string length before accessing: if (index >= 0 && index < str.length()) { char c = str.charAt(index); } else { /* handle error */ }
Check the string length before accessing: if (index >= 0 && index < str.length()) { char c = str.charAt(index); } else { /* handle error */ } -
80% success Use str.substring(start, end) with bounds checking, or use str.charAt(Math.min(index, str.length()-1)) as a temporary clamp.
Use str.substring(start, end) with bounds checking, or use str.charAt(Math.min(index, str.length()-1)) as a temporary clamp.
中文步骤
Check the string length before accessing: if (index >= 0 && index < str.length()) { char c = str.charAt(index); } else { /* handle error */ }Use str.substring(start, end) with bounds checking, or use str.charAt(Math.min(index, str.length()-1)) as a temporary clamp.
Dead Ends
Common approaches that don't work:
-
70% fail
This hides the bug and may cause downstream issues like null pointer exceptions or incorrect data processing.
-
85% fail
This does not address the root cause of incorrect index calculation; the index may still be out of range for other inputs.