java runtime_error ai_generated true

java.lang.StringIndexOutOfBoundsException: String index out of range: 10

ID: java/string-index-out-of-bounds-exception

Also available as: JSON · Markdown · 中文
88%Fix Rate
83%Confidence
1Evidence
2023-12-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
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.html

Workarounds

  1. 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 */ }
  2. 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.

中文步骤

  1. Check the string length before accessing: if (index >= 0 && index < str.length()) { char c = str.charAt(index); } else { /* handle error */ }
  2. 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:

  1. 70% fail

    This hides the bug and may cause downstream issues like null pointer exceptions or incorrect data processing.

  2. 85% fail

    This does not address the root cause of incorrect index calculation; the index may still be out of range for other inputs.