How to fix ArrayIndexOutOfBoundsException and StringIndexOutOfBoundsException in Java?

Though both StringIndexOutOfBoundsException and ArrayIndexOutOfBoundsException are children of IndexOfBoundsException class, the former is thrown by methods of String and related class like StringBuffer and StringBuilder to indicate that an index is either negative or greater than the size of the String, or more generally not valid. For example, charAt() method throws StringIndexOutOfBoundsException when an index is equal to the length of String? why? because String is backed by character array where index starts at 0 and ends at length -1

The ArrayIndexOutOfBoundsException is also quite similar to the former but thrown by code which deals with array access to indicate that array is accessed by an invalid index. The index is either negative or greater than or equal to the length of the array.

In this article, we will see some examples, where JDK throws ArrayIndexOutOfBoundsException and StringIndexOutOfBoundsException.




Similarities between StringIndexOutOfBoundsException and ArrayIndexOutOfBounds

Here are some common points between both StringIndexOutOfBoundsException and ArrayIndexOutOfBoundsException in Java:
  1. Both extends IndexOutOfBoundsException
  2. Both have constructors to create with message and invalid index
  3. You cannot cast ArrayIndexOutOfBoundsException to StringIndexOutOfBoundsException and vice-versa.
  4. Throw ArrayIndexOutOfBounds if you deal with an array, and throw StringIndexOutOfBoundsExeption if you deal with String.

You can also see Core Java Volume 1 - Fundamentals 10th Edition by Cay S. Horstmann to learn more about these two exceptions in Java. And, here are a couple of practical tips to avoid both StringIndexOutOfBoundException and ArrayIndexOutOfBoundxception in Java.

[Solved] How to Fix StringIndexOutOfBoundsException and ArrayIndexOutOfBoundsException in Java?



StringIndexOutOfBoundsException vs ArrayIndexOutOfBoundsException Example

Here is a sample Java program to demonstrate the difference between these two exceptions, both are the same i.e. they come when you try to access the invalid index. You get StringIndexOutOfBoundsException when you try to access the invalid index of String object using methods of String class.  

Similarly, when you try to access an invalid index of an array you get the java.lang.ArrayIndexOutOfBoundsException in Java is shown in the following example.

/**
 * Simple Java program to demonstrate difference between 
 * StringIndexOutOfBoundsException
 * vs ArrayIndexOutOfBoundsException
 * 
 * @author WINDOWS 10
 *
 */
public class TestString {


    public static void main(String[] args) {

        String brand = "Samsung Galaxy";
        
        // You get StringIndexOutOfBoundsException when you try
        // to access invalid index of a String in Java.
        // this will throw StringIndexOutOfBoundsException
        // because last character is at length - 1, not at length
        char lastChar = brand.charAt(brand.length());
        
        // but if try to access invalid index in array
        // you get ArrayIndexOutOfBoundsException
        
        char[] chars = brand.toCharArray();
        char firstChar = chars[1]; 
        // invalid index - ArrayIndexOutOfBoundsException
        
    }

}

Output
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: 
 String index out of range: 14
    at java.lang.String.charAt(String.java:658)
    at TestString.main(TestString.java:19)


That's all about how to fix java.lang.StringIndexOutOfBoundsException: String index out of range: 0 in Java. We have also learned about difference between StringIndexOutBoundsException and ArrayIndexOutOfBoundsException in Java. Just remember that the root cause of both errors is trying to access the invalid index.

 Most of the time its the first index in an empty array or fist character in an empty String that's why java.lang.StringIndexOutOfBoundsException: String index out of range: 0 is probably the most popular scenario of StirngIndexOutOfBoundException in Java. 

Other Related Error and Exception Tutorials for Java Programmers
  • java.lang.ClassNotFoundException : org.Springframework.Web.Context.ContextLoaderListener (solution)
  • java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet in Java Spring MVC Application [solution]
  • How to solve java.sql.BatchUpdateException: String or binary data would be truncated (guide)
  • How to solve java.lang.ClassNotFoundException: com.mysql.jdbc.Driver error? (hint)
  • 5 Reasons of NoClassDefFoundError in Java? (tutorial)
  • How to fix Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger (solution)
  • Cause of "java.lang.SecurityException: Missing required Permissions manifest attribute in main jar" [solution]
  • How to fix "illegal start of expression" compile time error in Java? (tutorial)
  • How to connect to MySQL database in Java? (tutorial)
  • How to fix "Error: Could not find or load main class" in Eclipse? (guide)
  • java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory error (solution)
  • java.sql.SQLException: No suitable driver found for 'jdbc:mysql://localhost:3306/mysql [Solution]
  • How to deal with "No JVM installation found, please install 64-bit JDK" error? (solution)
  • How to fix unable to find certification path error in Java SSL? (guide)
  • How to avoid ConcurrentModificationException in Java? (tutorial)
  • How to solve "could not create the Java virtual machine" error in Java? (solution)
  • Common reasons for java.lang.ArrayIndexOutOfBoundsException in Java? (solution)
  • 10 common reasons for java.lang.NumberFormatException in Java? (tutorial)
  • java.sql.SQLServerException: The index 58 is out of range - JDBC (solution)
  • Fixing java.lang.unsupportedclassversionerror unsupported major.minor version 50.0 (solution)
  • How to fix 'javac' is not recognized as an internal or external command (solution)
  • Cause and solution of "class, interface, or enum expected" compiler error in Java? (fix)
  • How to solve "variable might not have initialized" compile-time error in Java? (answer)
  • How to solve java.lang.classnotfoundexception oracle.jdbc.driver.oracledriver? (solution)

Thanks for reading this article so far. If you like this troubleshooting guide and my explanation of StirngIndexOutOfBoundException and ArrayIndexBoundOfExcepotion then please share it with your friends and colleagues. If you have any questions or feedback, please drop a comment.

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.