Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting arrays of a supertype to a subtype

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;
like image 981
luke657 Avatar asked Nov 23 '25 11:11

luke657


1 Answers

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[].

like image 121
Patricia Shanahan Avatar answered Nov 24 '25 23:11

Patricia Shanahan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!