why I can set primitive types to null in ternary operations

我怕爱的太早我们不能终老 提交于 2019-11-29 06:12:35

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.

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();

Indeed, autounboxing null leads to a NullPointerException.

So why the java-compiler doesn't fetch nonsense like this?

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...

Section 15.25 of the Java Language Specification explains how the type of the whole expression is determined.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!