java runtime_error ai_generated true

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

ID: java/stringindexoutofboundsexception

Also available as: JSON · Markdown · 中文
92%Fix Rate
87%Confidence
1Evidence
2023-04-05First Seen

Version Compatibility

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

Workarounds

  1. 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); }'
  2. 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);'

中文步骤

  1. Always check string length before accessing: 'if (index >= 0 && index < str.length()) { char c = str.charAt(index); }'
  2. 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:

  1. 90% fail

    Using String.charAt() without checking length first leads to this exception when the string is shorter than expected.

  2. 85% fail

    Assuming substring(start, end) works with end > length will throw this exception.