java ternary conditions strange null pointer exception [duplicate]

孤街醉人 提交于 2019-11-30 22:42:35

When you use ternary operator,

 flag  ? type1 : type2

Type1 and type2 must be of same type while conversion. First it realises type1 and then type2.

Now look at your cases

 final Integer b = false ? 0 : a;

Since type1 is 0 and it takes as a primitive and since a is trying to convert it as a primitive. Hence the null pointer.

where as same tricky test5

 final Integer b = false ? a : 0;

Since a is of type Integer 0 boxed to wrapper integer and assigned to the LHS.

I think in this case a will unboxed to an int, because 0 is an int . That means that null.intValue() is called and get an NPE

@Test
public void test1() {
    final Integer a = null;

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