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