Good code gray with conditional operator: bug?

Consider the following code:

           private @Nullable Integer foo(@Nullable String s, @Nullable Integer i) {
               return s == null? i : (Integer) 2;

IDEA highlights the "(Integer)" cast in gray and suggests that "Casting '2' to 'Integer' is redundant". The question is, is it really?

Without the cast, the type of the expression  "s == null ? i : 2" is going to be int (it chooses between a reference and int primitive and picks the int primitive, see JLS 15.25); so "i" will be unboxed to an int if it is chosen. If you call foo(null, null), the unboxing with throw a NPE.

With the cast, the type of "s == null ? i : (Integer) 2" is an Integer (both operands 2 and 3 are of type Integer) and so if i happens to be null, that's fine and that's what gets returned. So foo(null, null) returns null.

In one case we can call foo(null, null) and in the other it throws, so the cast doesn't seem unnecessary. Should IDEA not suggest it gets removed?

(Note: whether one would write "(Integer) 2" is another debate :) )


I agree with you....
Call with two null parameters will cause NPE


Hi Vincent,

Looks like a bug at the inspection processing. Created coresponding ticket at IJ tracker -



Please sign in to leave a comment.