Is there a particular reason why this results in runtime exception instead of compile-time error in Java?
Object[] objects = new Object[10];
String[] strings = (String[])objects;
The check has to be done at run time because of this case:
public class Test {
public static void main(String[] args){
String[] stringsBase = {"aaa", "bbb", "ccc"};
Object[] objects = stringsBase;
String[] strings = (String[])objects;
System.out.println(strings[1]);
}
}
This is a valid, working program. Without doing flow analysis, the compiler does not know whether objects references an array that was created as Object[], or one that was created as, in this case, a String[].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With