Java : ArrayStoreException with Examples

ArrayStoreException (Java SE 20 & JDK 20) API Examples.
You will find code examples on most ArrayStoreException methods.


Summary

Thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects.

Class diagram

String[] strings = new String[]{"aaa", "bbb", "ccc"};
System.out.println(Arrays.toString(strings)); // [aaa, bbb, ccc]

Object[] objects = strings;
objects[0] = "XXX";
objects[1] = "YYY";

System.out.println(Arrays.toString(strings)); // [XXX, YYY, ccc]

try {
    objects[2] = Integer.valueOf(123);
} catch (ArrayStoreException e) {
    System.out.println("ArrayStoreException! : " + e.getMessage());
}

// Result
// ↓
//ArrayStoreException! : java.lang.Integer

Please see also Java Language Specification :


Constructors

ArrayStoreException ()

Constructs an ArrayStoreException with no detail message.

final var e = new ArrayStoreException();
System.out.println(e); // java.lang.ArrayStoreException

ArrayStoreException (String s)

Constructs an ArrayStoreException with the specified detail message.

final var e = new ArrayStoreException("abcde");
System.out.println(e); // java.lang.ArrayStoreException: abcde
System.out.println(e.getMessage()); // abcde

Methods declared in Throwable

addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString

Please see the link below.


Related posts

To top of page