Java: unary if - npe

筅森魡賤 提交于 2019-12-25 03:56:08

问题


Why does this code can cause a NPE? Findbugs give me the hint, that this can occur and it does sometimes :-)

Any ideas?

public Integer whyAnNPE() {
    return 1 == 2 ? 1 : 1 == 2 ? 1 : null;
}

回答1:


EDIT: The code in the question wasn't present when I wrote this answer.

Here's another method to make it slightly clearer:

public static Integer maybeCrash(boolean crash) {
    return true ? (crash ? null : 1) : 0;
}

The important point is that we have two conditional expressions here. The inner one is of type Integer due to the last bullet point in the determination of the type as specified in section 15.25.

At that point, we've got a situation like this:

public static Integer maybeCrash(boolean crash) {
    Integer tmp = null;
    return true ? tmp : 0;
}

Now for the remaining conditional expression, the previous bullet point applies, and binary numeric promotion is performed. This in turn invokes unboxing as the first step - which fails.

In other words, a conditional like this:

condition ? null-type : int

involves potentially boxing the int to an Integer, but a conditional like this:

condition ? Integer : int

involves potentially unboxing the Integer to int.


Original answer

Here's a rather simpler example which is actually valid Java:

public class Test {
    public static void main(String[] args) {
        int x = args.length == 0 ? 1 : null;
    }
}

This is effectively:

int tmp;
if (args.length == 0) {
   tmp = 1;
} else {
   Integer boxed = null;
   tmp = boxed.intValue();
}

Obviously the unboxing step here will go bang. Basically it's because of the implicit conversion of a null expression to Integer, and from Integer to int via unboxing.



来源:https://stackoverflow.com/questions/7808117/java-unary-if-npe

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