Java: unary if - npe

2019-09-11 15: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条回答
孤傲高冷的网名
2楼-- · 2019-09-11 15:31

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.

查看更多
登录 后发表回答