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 对象,这是可以的。