Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullPointerException in ternary expression with null Long

Why does the following line of code produce a NullPointerException?

Long v = 1 == 2 ? Long.MAX_VALUE : (Long) null;

I understand that unboxing is being performed on null, but why?

Note that

Long v = (Long) null;

Does not produce the Exception.

like image 749
jonderry Avatar asked Dec 15 '11 02:12

jonderry


People also ask

Can we handle NullPointerException?

NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.

Can we extend NullPointerException in Java?

#5) Can we catch NullPointerException in Java? Answer: The exception java. lang. NullPointerException is an unchecked exception and extends RuntimeException class.

What does Java lang NullPointerException null mean?

NullPointerException is a runtime exception in Java that occurs when a variable is accessed which is not pointing to any object and refers to nothing or null. Since the NullPointerException is a runtime exception, it doesn't need to be caught and handled explicitly in application code.

What is ternary operator in Java with example?

Java ternary operator is the only conditional operator that takes three operands. It's a one-liner replacement for the if-then-else statement and is used a lot in Java programming. We can use the ternary operator in place of if-else conditions or even switch conditions using nested ternary operators.


1 Answers

So it looks obvious that you only have to box if the condition is true, and there should be no boxing if the condition is false. However the ternary operator expression must have a particular static type. So we have Long and long. The JLS states that the result will be the primitive (just as well - imagine if the operator was, say, + or even ==). So the ternary operator will force the unboxing, and only then does the assignment cause a boxing.

If you were to replace the code with the equivalent if-else, then you'd just have an assignment from long to Long and from Long to Long, which wouldn't have any unboxing and so run fine.

IIRC, this is covered is Bloch & Gafter's Java Puzzlers.

like image 91
Tom Hawtin - tackline Avatar answered Nov 09 '22 23:11

Tom Hawtin - tackline