Open In App

How to Fix a java.lang.StringIndexOutOfBoundsException?

Last Updated : 06 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

  • We need to ensure that the index we provide is within the valid range of length-1 of the string. (Using conditional Statement).
  • We can add the try. Catch into the statement of the logic of the program where the possibility can raise the exception of the string out of bound.

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

  • Create the Java class named as StringIndexOutBoundsExceptionExample1 and write the main class into it.
  • Assigning the string of the Hello World!
  • Then check the length of the string if access the character less than or equal to string then result as accessing character.
  • Otherwise, Print the message as result.

Implementation:

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


Output

Index out of bounds.

Explanation of the above Program:

  • We can handle the string out of the bounds using condition statement.
  • If the string length is greater than 20 then trying to access the character of the string in that case can print the Index out of bounds statement.

Approach 2: Using Try catch blocks

  • Create the Java class named as StringIndexOutBoundsExceptionExample2 and write the main class into it.
  • Assigning the string of the Hello World!
  • Add the try and catch of the program. If the access character is less than or equal to string, then print the character.
  • Otherwise, Print the error message as result.

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


Output

Caught StringIndexOutOfBoundsException: Index is out of bounds.

Explanation of the above Program:

  • We can handle the string out of the block exception using try catch block.
  • When the access of the character can be added the try block then using the catch statement can be catch the exception using StringIndexOutOfBoundsException.
  • Then print the exception error message as result.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads