[英]explanation needed: ternary operator in java
The line in question is return pFile.exists() ? true : null;
有问题的行是
return pFile.exists() ? true : null;
return pFile.exists() ? true : null;
. 。 As it does not raise any compilation error, what is the explanation for this.
因为它没有引起任何编译错误,对此有什么解释。 It ended up raising
NPE
. 它最终提高了
NPE
。
import java.io.File;
public class Main {
public static void main(String... args) {
boolean accept = accept(new File(""));
System.out.println("accept = " + accept);
}
public static boolean accept(File pFile) {
System.out.println(pFile.exists()); // prints: false, so pFile is not null
return pFile.exists() ? true : null; //this line should throw compilation error
}
}
pFile
is not null
; pFile
不为null
; a File
is instantiated as you can see. 如您所见,实例化
File
。 But obviously the file is not there. 但显然文件不存在。 The question is not about
pFile
. 问题不在于
pFile
。 I am interested in how the operator is dealing with null
. 我对运算符如何处理
null
感兴趣。
You code is equivalent to: 你的代码相当于:
public static boolean accept(File pFile) {
System.out.println(pFile.exists()); // prints: false, so pFile is not null
Boolean tmp = pFile.exists() ? true : null;
return (boolean) tmp;
}
On other words, the type of the conditional operator is Boolean
in this case, and then the value is being unboxed to return a boolean
. 换句话说,在这种情况下,条件运算符的类型是
Boolean
,然后该值被取消装箱以返回boolean
。 When null
is unboxed, you get an exception. 取消装箱为
null
,会出现异常。
From section 15.25 of the Java Language Specification: 从Java语言规范的15.25节 :
Otherwise, the second and third operands are of types S1 and S2 respectively.
否则,第二和第三操作数分别是S1和S2类型。 Let T1 be the type that results from applying boxing conversion to S1, and let T2 be the type that results from applying boxing conversion to S2.
设T1是将拳击转换应用于S1所产生的类型,让T2为应用到S2的装箱转换所产生的类型。 The type of the conditional expression is the result of applying capture conversion (§5.1.10) to lub(T1, T2) (§15.12.2.7).
条件表达式的类型是将捕获转换(第5.1.10节)应用于lub(T1,T2)(第15.12.2.7节)的结果。
I believe that's the case that's applicable here, although I'll grant it's not as clear as it might be. 我相信这是适用的情况,虽然我会认为它不是那么清楚。
You return Boolean null
from function defined as returning boolean
(a primitive type; note small b
). 从函数返回
Boolean null
定义为返回boolean
(基本类型;注意小b
)。 The null
value is automatically unboxed, and casues NPE. null
值自动取消装箱,并且会产生NPE。
Actually, an empty string is being used to create a file
. 实际上,正在使用空字符串来创建
file
。 This results in a empty abstract pathname
with no prefix(or directory) and an empty name sequence. 这会产生一个空的
abstract pathname
,没有前缀(或目录)和空名称序列。 So windows is unable to create a file
. 所以Windows无法创建
file
。 This in turn is throwing a NPE
这反过来又是一个
NPE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.