Java StringIndexOutOfBoundsException

Introduction

StringIndexOutOfBoundsException in Java is a runtime exception that occurs when an invalid index is used to access characters in a string.

Table of Contents

  1. What is StringIndexOutOfBoundsException?
  2. Common Causes
  3. How to Handle StringIndexOutOfBoundsException
  4. Examples
  5. Conclusion

1. What is StringIndexOutOfBoundsException?

StringIndexOutOfBoundsException is thrown when an index used to access a string is either negative or greater than or equal to the string’s length.

2. Common Causes

  • Accessing a character at an invalid index.
  • Using a negative index.
  • Using an index equal to or greater than the string’s length.

3. How to Handle StringIndexOutOfBoundsException

  • Validate Index: Ensure the index is within the valid range (0 to string length – 1).
  • Use String Methods: Utilize string methods like length() to check boundaries before accessing characters.

4. Examples

Example 1: Accessing a Character at an Invalid Index

This example demonstrates how StringIndexOutOfBoundsException occurs when accessing an invalid index.

public class InvalidIndexExample { public static void main(String[] args) { String text = "Hello, World!"; try { char ch = text.charAt(20); // Invalid index } catch (StringIndexOutOfBoundsException e) { System.out.println("Caught StringIndexOutOfBoundsException: " + e.getMessage()); } } } 

Example 2: Proper Index Validation

This example shows how to avoid StringIndexOutOfBoundsException by validating the index.

public class IndexValidationExample { public static void main(String[] args) { String text = "Hello, World!"; int index = 5; if (index >= 0 && index < text.length()) { char ch = text.charAt(index); System.out.println("Character at index " + index + ": " + ch); } else { System.out.println("Index out of bounds"); } } } 

5. Conclusion

StringIndexOutOfBoundsException in Java is a common exception that can be easily avoided by validating indices before accessing characters in a string. Proper handling ensures robust and error-free string operations in Java applications.

Leave a Comment

Scroll to Top