Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

ArrayStoreException is thrown at runtime in Java when an attempt is made to store the incorrect type of object in an array of objects. Since ArrayStoreException is an unchecked exception, it isn’t typical to handle or declare it.

In this tutorial, we’ll demonstrate the cause of ArrayStoreException, how to handle it, and best practices for avoiding it.

2. Causes of ArrayStoreException

Java throws an ArrayStoreException when we try to store a different type of object in an array instead of the declared type.

Suppose we instantiated an array with String type and later tried to store Integer in it. In this case, during runtime, ArrayStoreException is thrown:

Object array[] = new String[5];
array[0] = 2;

The exception will be thrown at the second line of code when we try to store an incorrect value type in the array:

Exception in thread "main" java.lang.ArrayStoreException: java.lang.Integer
    at com.baeldung.array.arraystoreexception.ArrayStoreExceptionExample.main(ArrayStoreExceptionExample.java:9)

Since we declared array as an Object, the compilation is error-free.

3. Handling the ArrayStoreException

The handling of this exception is pretty straightforward. As any other exception, it also needs to be surrounded in a try-catch block for handling:

try{
    Object array[] = new String[5];
    array[0] = 2;
}
catch (ArrayStoreException e) {
    // handle the exception
}

4. Best Practices to Avoid This Exception

It is recommended to declare the array type as a specific class, such as String or Integer, instead of Object. When we declare the array type as Object, then the compiler will not throw any error.

But declaring the array with the base class and then storing objects of a different class will lead to a compilation error. Let’s see this with a quick example:

String array[] = new String[5];
array[0] = 2;

In the above example, we declare the array type as String and try to store an Integer in it. This will lead to a compilation error:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
  Type mismatch: cannot convert from int to String
    at com.baeldung.arraystoreexception.ArrayStoreExampleCE.main(ArrayStoreExampleCE.java:8)

It’s better if we catch errors at compile-time rather than runtime as we have more control over the former.

5. Conclusion

In this tutorial, we learned the causes, handling, and prevention of ArrayStoreException in Java.

The complete example is available over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.