Given:

public class App {

    public static void main(String[] args) {
        Boolean[] bool = new Boolean[2];

        bool[0] = new Boolean(Boolean.parseBoolean("true"));
        bool[1] = new Boolean(null);

        System.out.println(bool[0] + " " + bool[1]);
    }
}

What is the result?

A.

true false

B.

true null

C. Compilation fails
D. A NullPointerException is thrown at runtime

題解

程式第 6 行,會產生內容為「true」的 Boolean 物件。

程式第 7 行,在 Boolean 類別的建構子參數傳入 null 會產生內容為「false」的 Boolean 物件,這部份可以參考 Java 的原始碼:

public Boolean(boolean value) {
    this.value = value;
}
public Boolean(String s) {
    this(parseBoolean(s));
}
public static boolean parseBoolean(String s) {
    return ((s != null) && s.equalsIgnoreCase("true"));
}