Open In App

How to Fix a java.lang.StringIndexOutOfBoundsException?

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.



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.

Program to Fix a java.lang.StringIndexOutOfBoundsException

Below are the step-by-step implementations of the two approaches to fix a java.lang.StringIndexOutOfBoundsException.

Approach 1: Using Conditional Statement

Implementation:




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.");
        }
    }
}

Output
Index out of bounds.

Explanation of the above Program:

Approach 2: Using Try catch blocks

Implementation:




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();
        }
    }
}

Output
Caught StringIndexOutOfBoundsException: Index is out of bounds.

Explanation of the above Program:


Article Tags :