Given the code fragment:
public class Test {
public static void main(String[] args) {
// line n1
switch (x) {
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
}
}
}
Which three code fragments can be independently inserted at line nl to enable the code to print one?
A.
Byte x = 1;
B.
short x = 1;
C.
String x = "1";
D.
Long x = 1;
E.
Double x = 1;
F.
Integer x = new Integer("1");
題解
從 switch 內的 case 來看,可以發現用於 case 的值為整數數值,所以 x 變數為整數型態的變數。但題目選項有使用到 Wrapper 類別,這裡要注意到 Java 的整數數值預設為 int 型態,但它能夠自動向下轉型至 short 或是 byte。所以也可以自動轉型(autoboxing)成 Integer、Short 或是 Byte 物件。
選項 A,數字「1」可自動轉型成 Byte 物件。
選項 B,數字「1」可自動轉型成 short 基本資料型態。
選項 C,這裡的 switch 並不是使用字串型態的變數。
選項 D,數字「1」不可以自動轉型成 Long 物件,就算改成「1L」,switch 也不能使用 Long 型態。
選項 E,數字「1」不可以自動轉型成 Double 物件。
選項 F,使用字串「1」來產生 Integer 物件,這是可以的。
