This piece of code works fine :-
Integer nullInt = null; 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?
The conditional operator – also known as the ternary operator – is an alternative form of the if/else statement that helps you to write conditional code blocks in a more concise way. First, you need to write a conditional expression that evaluates into either true or false .
Emphasis: value-selection before/after action needing values. There's a different emphasis: An if / else statement emphasises the branching first and what's to be done is secondary, while a ternary operator emphasises what's to be done over the selection of the values to do it with.
Except in very simple cases, you should discourage the use of nested ternary operators. It makes the code harder to read because, indirectly, your eyes scan the code vertically.
The fastest is the basic ternary operator, followed by the if-else statement and then by the ternary expression with a tuple.
Autoboxing and unboxing lets developers write cleaner code, making it easier to read. The technique let us use primitive types and Wrapper class objects interchangeably and we do not need to perform any typecasting explicitly.
Assigned to a variable of the corresponding wrapper class. Unboxing: Converting an object of a wrapper type to its corresponding primitive value is called unboxing. For example conversion of Integer to int.
Advantages of Autoboxing / Unboxing: Autoboxing and unboxing lets developers write cleaner code, making it easier to read. The technique let us use primitive types and Wrapper class objects interchangeably and we do not need to perform any typecasting explicitly.
Another example of auto and unboxing is to find sum of odd numbers in a list. Important point in the program is that the operators remainder (%) and unary plus (+=) operators do not apply to Integer objects.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With