ArrayStoreException in java

ArrayStoreException is a run time exception which is thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects.

Class Hierarchy of ArrayStoreException:

java.lang.Object
↳ java.lang.Throwable
    ↳ java.lang.Exception
        ↳ java.lang.RuntimeException
            ↳ java.lang.ArrayStoreException 

Constructors of ArrayStoreException:

  • public ArrayStoreException()

    It is used to construct an ArrayStoreException with no message.

  • public ArrayStoreException(String s)

    It is used to construct an ArrayStoreException with the specified message.

Example

public class Main {
 
    public static void main(String[] args) {
       Object[] stringArray = new String[4];        
       stringArray[1] = "w3schools"; 
       //java.lang.ArrayStoreException here
       stringArray[2] = 20;
    }
}

Output

Exception in thread "main" java.lang.ArrayStoreException: java.lang.Integer
        at Main.main(Main.java:7)

How to handle with ArrayStoreException?

We can use try, catch or throws keywords to handle ArrayStoreException.

Example

public class Main {
 
    public static void main(String[] args) {
        try{
             Object[] stringArray = new String[4];        
            stringArray[1] = "w3schools"; 
            //java.lang.ArrayStoreException here
            stringArray[2] = 20;
        }catch(ArrayStoreException e){
            e.printStackTrace();
        }
 
    }
}

Output

java.lang.ArrayStoreException: java.lang.Integer
        at Main.main(Main.java:8)

Java interview questions on Exception Handling