Java return null for primitive in ternary [duplicate]

回眸只為那壹抹淺笑 提交于 2019-12-01 09:06:23

The type of the ternary conditional operator is determined by the types of its 2nd and 3rd operands.

In the case of

input == null ? null : 1

the type is Integer, which can be assigned both null and 1.

The compiler allows your method to return an Integer since it can be auto-unboxed into an int, so it fit the int return type of myMethod.

The fact that your specific code may throw a NullPointerException is not something the compiler can detect.

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