Given the code fragment:



public static void main(String[] args) {
    Short s1 = 200;
    Integer s2 = 400;
    Long s3 = (long) s1 + s2; // line n1
    String s4 = (String) (s3 * s2); // line n2
    System.out.println("Sum is " + s4);
}

What is the result?

A. Sum is 600
B. Compilation fails at line n1.
C. Compilation fails at line n2.
D. A ClassCastException is thrown at line n1.
E. A ClassCastException is thrown at line n2.

題解

line n2的「(s3 * s2)」無法強制轉型至String物件,原因在於數值和字串並沒有人任何的繼承關係,因此會發生編譯錯誤。

至於Wrapper類別與基本數值資料型別在正確的在型別的空間大小下,可以互相轉型,也能自動轉型(auto wrapping)。

若轉型的型態和要轉型的物件有繼承關係,在執行階段才會檢查物件實體的型態,如果無法轉型,會拋出ClassCastException例外。