Last Updated : 06 Mar, 2024
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.
StringIndexOutOfBoundsExceptionIt 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.
Approach 1: Using Conditional StatementImplementation:
Java
import java.io.*;
public class StringIndexOutOfBoundsExceptionExample1
{
public static void main(String[] args) {
String str = "Hello, World!";
// Checking if index is within bounds
if (str.length() > 20) {
char ch = str.charAt(20);
System.out.println(ch);
} else {
System.out.println("Index out of bounds.");
}
}
}
Index out of bounds.Explanation of the above Program:
Implementation:
Java
import java.io.*;
public class StringIndexOutOfBoundsExceptionExample2 {
public static void main(String[] args) {
String str = "Hello, World!";
try {
char ch = str.charAt(20); // Trying to access index out of bounds
System.out.println("Character at index 20: " + ch);
} catch (StringIndexOutOfBoundsException e) {
System.out.println("Caught StringIndexOutOfBoundsException: Index is out of bounds.");
// You can handle the exception here, e.g., by providing a default value
// char ch = getDefaultChar();
}
}
}
Caught StringIndexOutOfBoundsException: Index is out of bounds.Explanation of the above Program:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4