有人可以解释为什么这段 Java 代码可以编译吗?
public class Main {
public static void main(String []args){
System.out.println(foo(true));
System.out.println(foo(false));
}
public static boolean foo(boolean value) {
// this should make the compiler say something, at least complain a bit...
return value ? true : null;
}
}
最佳答案
正如 Oliver 在评论中所说,这个编译的原因是自动装箱。
null
可以自动装箱为 Boolean
,可以自动拆箱为 boolean
,让编译器满意。在运行时,自动装箱有效,但当它被拆箱为 boolean
时,它将抛出 NullPointerException
。
关于java - 这段 Java 代码如何编译无误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43073089/