为什么我可以在三元操作中将原始类型设置为null [英] why I can set primitive types to null in ternary operations
问题描述
我一直认为Java中的原始类型不能是 null
,因为如果我尝试这样做是一个编译时错误:
I always thought that primitive types in Java cannot be null
, as it is a compile time error if i attempt to do something like this:
int test = null;
然而,在三元操作中,似乎是允许的:
However in a ternary operation, it seems to be allowed:
int test = something != 0 ? 5 : null;
这不是三元操作(在这种情况下):
Isn't a ternary operation just short for (in this case):
int test;
if (something != 0){
test = 5;
} else {
test = null
}
当然不应该被允许。如果该条件失败,由于自动装箱,它将自动抛出 NullPointerException
。那么为什么java编译器不会像这样获取废话?
which of course should not be allowed. if that condition fails, It will automaticly throw a NullPointerException
due to autoboxing. So why the java-compiler doesn't fetch nonsense like this?
推荐答案
Java编译器首先尝试制作:
两侧的表达式类型相等。在这种情况下,它会将 5
自动装箱到整数
;请注意 null
是 Integer
的有效值。整个三元表达式的结果是 Integer
。您将其分配给 int
,然后整数
然后自动装箱。
What happens is that the Java compiler first tries to make the types of the expressions on either side of the :
equal. In this case, it autoboxes the 5
to an Integer
; note that null
is a valid value for Integer
. The result of the whole ternary expression is Integer
. You assign that to an int
, so the Integer
is then autounboxed.
本质上,编译器应用自动装箱和-unboxing,以便该行看起来像这样:
Essentially the compiler applies autoboxing and -unboxing so that the line is going to look like this:
int test = (something != 0 ? Integer.valueOf(5) : null).intValue();
的确,autounboxing null
会导致 NullPointerException
。
Indeed, autounboxing null
leads to a NullPointerException
.
那么为什么java编译器不会像这样获取废话?
So why the java-compiler doesn't fetch nonsense like this?
因为Java语言的设计者以这样的方式定义了语言,所以它没有决定这样做被视为错误......
Because the designers of the Java language defined the language in such a way that it works like this and didn't decide that this has to be treated as an error...
第15.25节解释了如何确定整个表达式的类型。
Section 15.25 of the Java Language Specification explains how the type of the whole expression is determined.
这篇关于为什么我可以在三元操作中将原始类型设置为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!