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"));
}