Solving ArrayStoreException in Java

Learn why we get the ArrayStoreException while working with arrays in Java and how to identify the root cause and fix this error.

1. Root Cause of ArrayStoreException

Java arrays are covariant and support the subtyping rules of Java, an array of type T[] may contain elements of type T or any subtype of T. For example, Integer is a subtype of Number so we can assign an Integer value into a Number array.

Number[] numbers = new Number[3];
numbers[0] = new Integer(10);  // Works Fine.

Java also allows an array S[] to be a subtype of the array T[] if S is a subtype of T.

Integer[] intArray = { 1, 2, 3, 4 };
Number[] numArray = intArray;
numArray[0] = 10;  // Works Fine.

Now consider, we try to trick the compiler and try to store a floating-point number in the above array.

numArray[0] = 10.01; 

The above code will fail and will give java.lang.ArrayStoreException: java.lang.Double error in runtime. Even though 10.01 is a number, java runtime clearly knows that Number[] numArray is only a reference variable and the actual array is of type Integer[]. So Java runtime will allow only the Integer values in the array.

So the root cause of the ArrayStoreException is attempting to store an incompatible type of value in an array. The type checking may be tricked during the compile-time, perhaps unknowingly, but the Java runtime will catch this attempt and it will throw the ArrayStoreException.

2. Solution

2.1. Manually analyze and fix

  1. Once we know the error, we can solve it easily. We have to closely check the code in the line where the exception has been reported in the application logs. Once we fix the datatype of the value and store a value of the compatible type in the array, the exception will be resolved.
  2. For some reason, if we do not have control over the values passed to the array, another option is to use try-catch block such code and take appropriate action if such incompatible value type is found.

2.2. Additonal Type Checking

Another option is to have additional type checking before adding the item to the array. If the item is of incompatible type then let the array store it; else just reject the value with some user-friendly error handler.

Integer[] intArray = { 1, 2, 3, 4 };
double value = 10.01;
	== ((Object)value).getClass()) {
  numArray[0] = value; 
} else {
  System.out.println("Incompatible type");

3. Conclusion

In this short tutorial, we learned why we get the ArrayStoreException in Java and how we can fix the issue. Though manually fixing the code is the proper solution, still having additional type checking will make the code more robust.

Happy Learning !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

Leave a Comment


A blog about Java and related technologies, the best practices, algorithms, and interview questions.