![]() |
VOOZH | about |
In Java, String index out of bound is the common runtime exception that can occur when we try to access or manipulate the string using the invalid index. It can typically happen when the index provides is the negative, equal length of the string or greater than the length of the string. It can be handled using StringIndexOutOfBoundsException and it is a pre-defined exception of the java.lang package.
In this article, we will learn how to fix a java.lang.StringIndexOutOfBoundsException.
It is a runtime exception in Java that can occur when we try to access the character in a string using an invalid index. It indicates that the index provided is either negative or equal to the length of the string.
Example Program:
public class StringIndexOutOfBoundsExceptionExample {
public static void main(String[] args) {
String str = "Hello, World!";
// Trying to access index out of bounds
char ch = str.charAt(20); // Throws StringIndexOutOfBoundsException
System.out.println(ch);
}
}
In the above example, we can try to access the character at the index of 20 in the string "Hello World!" It has a length of 13 characters. In this case result can be StringIndexOutOfBoundsException because we can try to access the index 20 is out of bounds.
We can fix this issue with two approaches.
Below are the step-by-step implementations of the two approaches to fix a java.lang.StringIndexOutOfBoundsException.
Implementation:
Index out of bounds.
Implementation:
Caught StringIndexOutOfBoundsException: Index is out of bounds.