Java : StringIndexOutOfBoundsException with Examples

StringIndexOutOfBoundsException (Java SE 21 & JDK 21) with Examples.
You will find code examples on most StringIndexOutOfBoundsException methods.


Summary

Thrown by String methods to indicate that an index is either negative or greater than the size of the string. For some methods such as the charAt method, this exception also is thrown when the index is equal to the size of the string.

Class diagram

final var str = "abc";

System.out.println(str.charAt(0)); // a
System.out.println(str.charAt(1)); // b
System.out.println(str.charAt(2)); // c

try {
    final var ret = str.charAt(3);
} catch (StringIndexOutOfBoundsException e) {
    System.out.println(e);
}

// Result
// ↓
//java.lang.StringIndexOutOfBoundsException: Index 3 out of bounds for length 3

Constructors

StringIndexOutOfBoundsException ()

Constructs a StringIndexOutOfBoundsException with no detail message.

final var e = new StringIndexOutOfBoundsException();
System.out.println(e); // java.lang.StringIndexOutOfBoundsException

StringIndexOutOfBoundsException (int index)

Constructs a new StringIndexOutOfBoundsException class with an argument indicating the illegal index.

final var e = new StringIndexOutOfBoundsException(123);

// java.lang.StringIndexOutOfBoundsException: String index out of range: 123
System.out.println(e);

StringIndexOutOfBoundsException (String s)

Constructs a StringIndexOutOfBoundsException with the specified detail message.

final var e = new StringIndexOutOfBoundsException("abcd");
System.out.println(e); // java.lang.StringIndexOutOfBoundsException: abcd

Methods declared in Throwable

addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString

Please see the link below.


Related posts

To top of page