Exception in thread "main" java.lang.arrayindexoutofboundsexception

Leader posted 7 min read

Today, we'll discuss about a Runtime Exception, “Exception in thread "main" java.lang.arrayindexoutofboundsexception” in Java. Java supports manipulation as well as creation of Arrays as a data structure. It's the most common data structure we learned as a beginner. This problem occurs when we try to access the index which doesn't exist in the array. Therefore, the way to avoid this exception is to make sure we access the array index correctly.

Note Array with length of N consists of indices from 0 to N-1 only.

What is "Exception in thread "main" java.lang.arrayindexoutofboundsexception" #

ArrayIndexOutOfBoundsException is a Runtime Exception in Java that is thrown only during runtime. The compiler will not check for this error during compilation. What it means is that: Whenever you're accessing indices that doesn't exist in the array, there's no red line on your code. However, it'll be thrown during runtime. See the example below:


  public static void main(String[] args) {
        // TODO code application logic here
        int[]array = {1,2,3,4,5,6};
        for(int i = 0; i <= array.length; i++){
            System.out.println(array[i]);
        }
    } 
  </span>

We didn't get any Compilation error, right? Let's see the output:


1
2
3
4
5
6
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 6
at labviva.NewMain.main(NewMain.java:21)
C:\Users\MC\Documents\NetBeansProjects\LabViva\nbproject\build-impl.xml:1341: The following error occurred while executing this line:
C:\Users\MC\Documents\NetBeansProjects\LabViva\nbproject\build-impl.xml:936: Java returned: 1
BUILD FAILED (total time: 1 second)
  

The error occurs! Why? Because it's a Runtime Error, not a Compilation error. We've requested the index which is inappropraite. So, what's the exact causes of this problem? Let's see the next section.

Causes #

From the above examples, there're two possible causes of this error, we'll look at them one by one:

  1. Request negative index from an array
    
            public static void main(String[] args) {
            // TODO code application logic here
            int[]array = {1,2,3,4,5,6};
            System.out.println(array[-1]);
        }
          

    This is the output:

    
            Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 6
    at labviva.NewMain.main(NewMain.java:20)
    C:\Users\MC\Documents\NetBeansProjects\LabViva\nbproject\build-impl.xml:1341: The following error occurred while executing this line:
    C:\Users\MC\Documents\NetBeansProjects\LabViva\nbproject\build-impl.xml:936: Java returned: 1
    BUILD FAILED (total time: 1 second)
          

    Why? This is due to the reason that we're accessing a negative index from an array, but every array has only indices in the interval [0, N-1], Where N is the length of array. Now, let's move on to the second cause.

  2. Request integer greater than or equal to length of an array
    
            public static void main(String[] args) {
            // TODO code application logic here
            int[]array = {1,2,3,4,5,6};
            System.out.println(array[array.length]);
        }
          

    This is the output:

    
            Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 6
    at labviva.NewMain.main(NewMain.java:20)
    C:\Users\MC\Documents\NetBeansProjects\LabViva\nbproject\build-impl.xml:1341: The following error occurred while executing this line:
    C:\Users\MC\Documents\NetBeansProjects\LabViva\nbproject\build-impl.xml:936: Java returned: 1
    BUILD FAILED (total time: 2 seconds)
          

    Let's see another example:

    
            public static void main(String[] args) {
            // TODO code application logic here
            int[]array = {1,2,3,4,5,6};
            System.out.println(array[array.length + 1]);
        } 
          

    This is the output:

    
            Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 7 out of bounds for length 6
    at labviva.NewMain.main(NewMain.java:20)
    C:\Users\MC\Documents\NetBeansProjects\LabViva\nbproject\build-impl.xml:1341: The following error occurred while executing this line:
    C:\Users\MC\Documents\NetBeansProjects\LabViva\nbproject\build-impl.xml:936: Java returned: 1
    BUILD FAILED (total time: 1 second)
          

    Why? The concept is same as the first cause but just accessing the index more than N-1, where N is the length of the array.

  3. Don't worry or feel frustrated, we'll now move on to the solution.

Solution #

There's only one solution for this Runtime Exception, which is pretty simple and fast. Let's look at the example together:


            public static void main(String[] args) {
        // TODO code application logic here
        int[]array = {1,2,3,4,5,6};
        for(int i = 0; i < array.length; i++){
            System.out.println("Index " + i + ": " + array[i]);
        }
    }
      

This is the output:


Index 0: 1
Index 1: 2
Index 2: 3
Index 3: 4
Index 4: 5
Index 5: 6
      

From the above example, we're using a for-loop to iterate each element of the array using its index, array[i]. You may notice that the array has length of 6 and we're iterating it from indices 0 to 5, which is complying with the rule: Only request index of an array in the interval [0, N-1], where N is the length of array. The loop will stop when the value of i is equal to the array length, and hence ArrayIndexOutOfBoundsException will not happen.

You may also do so:


public static void main(String[] args) {
        // TODO code application logic here
        int[]array = {1,2,3,4,5,6};
        for(int i = 0; i <= array.length - 1; i++){
            System.out.println("Index " + i + ": " + array[i]);
        }
    }
      </span>

It'll also render the exact same output as above.

The Conclusion #

In this study blog, we've learned about what's “Exception in thread "main" java.lang.arrayindexoutofboundsexception” in Java. Besides, we've known what is the causes of this exception and how to solve it simply. Just to remind again, we can only access the indices of an array in the interval [0, N-1], where N is the length of the array. Otherwise, this exception will be thrown during runtime.

The Reference #

You may go through this reference for more information:

  1. Arrays: https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html
  2. ArrayIndexOutOfBoundsException: https://docs.oracle.com/javase/7/docs/api/java/lang/ArrayIndexOutOfBoundsException.html
If you read this far, tweet to the author to show them you care. Tweet a Thanks

More Posts

IO class in Java 25

Pravin - Sep 22

Huffman Encoding Algorithm Using a Greedy Approach in Java

Aditya Pratap Bhuyan - Jun 15

How to Filter a Collection Using Streams in Java?

Aditya Pratap Bhuyan - Jun 8

Handling Large Graphs in Java with Streams: Patterns, Challenges, and Best Practices

Aditya Pratap Bhuyan - Jun 8

Can we access a final variable before initialization in Java?

Pravin - May 10
chevron_left