Storing a value in an array at run time causes a check that the type stored is compatible with the element type of the array.
The code below compiles without errors, but when it is run we get:
Exception in thread "main" java.lang.ArrayStoreException:
java.lang.Integer
at ex3.main(ex3.java:10)
1 public class ex3
2 {
3
4 public static void main(String[] args)
5 {
6 Object[] s = new String[3]; // A String is an Object
7
8 s[0] = "hello";
9 s[1] = "goodbye";
10 s[2] = new Integer(42); // An Integer is an Object, but is not a String
11
12 for(int i = 0; i < s.length; i++) {
13 System.out.println(s[i]);
14 }
15 }
16
17 }