Auto-unboxing need of ternary if-else

91StarSky :

This piece of code works fine :-

    if (1 <= 3) {
        Integer secondNull = nullInt;
    } else {
        Integer secondNull = -1;
    }
    System.out.println("done");

But this throws null-pointer exception, while Eclipse warning that there is need for auto-unboxing :-

    Integer nullInt = null;
    Integer secondNull = 1 <= 3 ? nullInt : -1;
    System.out.println("done");

Why is that so, can somebody guide please?

Eran :

The type of the ternary conditional expression

1 <= 3 ? nullInt : -1

is int (the JLS contains several tables that describe the type of the ternary conditional operator depending on the types of the 2nd and 3rd operands).

Therefore, when it tries to unbox nullInt to an int, a NullPointerException is thrown.

In order to get the behavior of your if-else snippet, you need to write:

1 <= 3 ? nullInt : Integer.valueOf(-1)

Now the type of the expression will be Integer, so no unboxing will take place.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=23111&siteId=1