ArrayStoreException in Java
In this tutorial, we will learn how to fix java.lang.ArrayStoreException that occurs when an object of an incompatible runtime type is stored in an array. The exception is common when a specific array, such as Float[] or String[], is assigned to a broader reference type such as Object[], and then a value of the wrong type is inserted.
ArrayStoreException is a runtime exception. The Java compiler may allow the assignment because arrays are covariant, but the Java runtime still checks the real array type before storing each element. If the value cannot be stored safely in that array, Java throws ArrayStoreException.
What java.lang.ArrayStoreException means in Java arrays
java.lang.ArrayStoreException means that the array object exists and the index is valid, but the value being stored is not compatible with the actual array type. This is different from ArrayIndexOutOfBoundsException, where the problem is an invalid index.
For example, a Float[] array can store Float objects. It cannot store an Integer object, even if the array is currently referenced through an Object[] variable.
Object[] values = new Float[2];
values[0] = 10.5f; // OK: Float value
values[1] = Integer.valueOf(2); // Not OK: Integer in a Float[] array
The important point is that the runtime array type is still Float[]. The variable type Object[] does not change what the array can actually store.
Java ArrayStoreException example with Object[] and Float[]
java.lang.ArrayStoreException occurs when we try to store an object of a type in an array of objects of different type. Usually, one would come across “java.lang.ArrayStoreException: java.lang.Integer” which occurs when an attempt is made to store an integer in an array of different type like array of String or array of float, etc.
Lets see a sample program that could produce this exception.
ArrayStoreExceptionExample.java
package com.tutorialkart.java;
/**
* @author tutorialkart.com
*/
public class ArrayStoreExceptionExample {
public static void main(String[] args) {
Object[] names = new Float[2];
names[1] = new Integer(2);
}
}
And when this program is run, following would be the result.
Output
Exception in thread "main" java.lang.ArrayStoreException: java.lang.Integer
at com.tutorialkart.java.ArrayStoreExceptionExample.main(ArrayStoreExceptionExample.java:9)
Let us see the first line of stack trace, java.lang.ArrayStoreException: java.lang.Integer, in detail.
java.lang.ArrayStoreException: Exception thrown by Java when the value being stored is not compatible with the actual runtime type of the array.java.lang.Integer: The type of object that the program tried to store.new Float[2]: The actual array type. This array can storeFloatvalues, notIntegervalues.ArrayStoreExceptionExample.java:9: The line where the incompatible value was assigned to the array.
Why Object[] names = new Float[2] can still fail
The line Object[] names = new Float[2]; is legal because Java arrays are covariant. That means a Float[] can be treated as an Object[], since every Float is also an Object.
However, covariance does not mean the array can store every kind of object. The array was created as new Float[2], so Java remembers its actual component type at runtime. When new Integer(2) is stored in it, Java rejects the assignment and throws ArrayStoreException.
| Code | Compile-time reference type | Runtime array type | Can store Integer? |
|---|---|---|---|
Object[] a = new Object[2]; | Object[] | Object[] | Yes |
Object[] a = new Float[2]; | Object[] | Float[] | No |
Number[] a = new Number[2]; | Number[] | Number[] | Yes |
Number[] a = new Float[2]; | Number[] | Float[] | No |
How to fix ArrayStoreException in Java
The correct fix is to make the array type and the values stored in it agree with each other. A try-catch block can stop a program from terminating, but it does not correct the type design that caused the exception.
Fix ArrayStoreException by using the correct array component type
If the array should store only floating-point values, use Float[] as the reference type and store only Float values.
Float[] values = new Float[2];
values[0] = 10.5f;
values[1] = 2.0f;
This is clearer than assigning new Float[2] to an Object[] reference because the compiler can now help prevent wrong assignments.
Fix ArrayStoreException by choosing Object[] only for mixed object types
If the array is meant to store different object types, create it as an actual Object[]. In that case, the runtime array type allows any object reference.
Object[] values = new Object[3];
values[0] = "Java";
values[1] = Integer.valueOf(2);
values[2] = Float.valueOf(10.5f);
Use this only when mixed types are part of the program design. If all values should be of one type, a specific array type is usually easier to maintain.
Fix ArrayStoreException by using Number[] for numeric values
If the array should store different numeric wrapper types, such as Integer, Float, and Double, create the array as Number[].
Number[] numbers = new Number[3];
numbers[0] = Integer.valueOf(2);
numbers[1] = Float.valueOf(10.5f);
numbers[2] = Double.valueOf(7.25);
This works because Integer, Float, and Double are subclasses of Number, and the runtime array type is actually Number[].
Fix ArrayStoreException by preferring generics for collection code
For many application-level tasks, a generic collection is safer than assigning a specific array to a broad array reference. A List<Float> clearly communicates that only Float values should be added.
java.util.List<Float> values = new java.util.ArrayList<>();
values.add(10.5f);
values.add(2.0f);
// values.add(Integer.valueOf(2)); // Compile-time error
With generics, many type mistakes are caught at compile time instead of appearing as runtime exceptions.
ArrayStoreException with System.arraycopy()
ArrayStoreException can also occur when copying from one array to another using System.arraycopy(). The destination array must be able to store every copied element from the source range.
Object[] source = {"Java", Integer.valueOf(10)};
String[] destination = new String[2];
System.arraycopy(source, 0, destination, 0, source.length);
// Fails because Integer cannot be stored in String[]
To fix this, use a destination array whose component type can hold all copied values, or copy only the compatible elements after checking their type.
Object[] source = {"Java", Integer.valueOf(10)};
Object[] destination = new Object[2];
System.arraycopy(source, 0, destination, 0, source.length);
How to Handle ArrayStoreException?
Lets handle the ArrayStoreException using try-catch.
- Surround the statements that could throw ArrayStoreException with try-catch block.
- Catch ArrayStoreException.
- Take necessary action for the further course of your program, as you are handling the exception and the execution doesn’t abort.
ArrayStoreExceptionExample.java
package com.tutorialkart.java;
/**
* @author tutorialkart.com
*/
public class ArrayStoreExceptionExample {
public static void main(String[] args) {
Object[] names = new Float[2];
try {
names[1] = new Integer(2);
} catch (ArrayStoreException e) {
e.printStackTrace();
System.out.println("The stack trace has been printed just for logging.");
System.out.println("ArrayStoreException is handled.");
}
System.out.println("Continuing with the statements after try-catch block.");
}
}
And when you run this java program, result would be as shown in the following.
Output
java.lang.ArrayStoreException: java.lang.Integer
at com.tutorialkart.java.ArrayStoreExceptionExample.main(ArrayStoreExceptionExample.java:10)
The stack trace has been printed just for logging.
ArrayStoreException is handled.
Continuing with the statements after try-catch block.
When an exception occurs, the execution falls on to the catch block from the point of occurrence of exception. It executes the statement in catch block and continues with the statement present after the try-catch block. So, care has to be taken while handling the exceptions and deciding on the further course of action in your program.
In real code, catch ArrayStoreException only when you can recover meaningfully. For example, you may log an invalid plugin value, reject an incompatible input item, or fall back to a safer conversion path. If the array type is wrong inside your own code, change the array declaration instead of depending on the catch block.
ArrayStoreException debugging checklist for Java code
- Check the line in the stack trace where the array assignment or
System.arraycopy()call occurs. - Print or inspect the actual array class using
array.getClass().getName()when a broad reference such asObject[]hides the real type. - Confirm the runtime type of the value being stored, especially when it comes from parsing, reflection, deserialization, plugins, or API responses.
- Replace broad array references with specific types where possible, such as
Float[],String[], orNumber[]. - Use generic collections when compile-time type safety is more useful than array covariance.
Object[] values = new Float[2];
Object item = Integer.valueOf(2);
System.out.println("Array runtime type: " + values.getClass().getName());
System.out.println("Item runtime type: " + item.getClass().getName());
Array runtime type: [Ljava.lang.Float;
Item runtime type: java.lang.Integer
ArrayStoreException versus ClassCastException in Java
ArrayStoreException happens while storing a value into an array. ClassCastException happens while casting an object reference to an incompatible type. Both are type-related runtime exceptions, but they occur at different operations.
| Exception | Usually happens when | Example operation |
|---|---|---|
ArrayStoreException | Storing an incompatible value in an array | values[0] = item |
ClassCastException | Casting an object to an incompatible class | String s = (String) item |
Frequently asked questions on ArrayStoreException in Java
How do I fix ArrayStoreException in Java?
Fix it by storing only values that match the actual runtime component type of the array. If the array is Float[], store Float values. If mixed objects are required, create the array as Object[]. If mixed numeric values are required, use Number[].
Why does Object[] values = new String[2] allow compilation but fail at runtime?
It compiles because Java arrays are covariant. A String[] can be assigned to an Object[] reference. It can still fail at runtime because the actual array is a String[], so Java will not allow a non-String object to be stored in it.
Can primitive arrays throw ArrayStoreException?
ArrayStoreException is mainly seen with reference type arrays such as Object[], String[], Number[], or Float[]. Primitive arrays such as int[] do not store object references, and incompatible primitive assignments are normally rejected by the compiler.
Can System.arraycopy() throw ArrayStoreException?
Yes. If any element copied from the source array cannot be stored in the destination array type, System.arraycopy() can throw ArrayStoreException. Use a compatible destination array or validate the elements before copying.
Should I catch ArrayStoreException or change the array declaration?
In most cases, change the array declaration or the value being stored. Catching the exception is useful only when the value comes from an external source and your program has a safe recovery step, such as skipping the incompatible item or reporting a validation error.
Conclusion: fixing java.lang.ArrayStoreException safely
In this Java Tutorial, we have learnt to fix java.lang.ArrayStoreException that occurs when an object of a different type is made to be stored in an array of a type. The practical rule is to check the actual array type, not only the reference type. Use a specific array type when all elements have the same type, use Object[] or Number[] only when that is truly the intended design, and prefer generic collections when compile-time type safety is more helpful.
TutorialKart.com