Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why NullPointerException occur in short IF [duplicate]

I written short Java code which cause NullPointerException. Does anybody have explanation for this? Code:

int val = 2;
Boolean result = (val == 0) ? false : ((val == 1) ? true : null);

Also following (simplified version) code will cause NullPointerException:

Object result = (false) ? false : (false ? true : null);

But this:

int val = 2;
Boolean result = (val == 0) ? Boolean.FALSE : ((val == 1) ? true : null);

and this:

Object result = (false) ? Boolean.FALSE : (false ? true : null);

or this:

Object result = (false) ? (Boolean)false : (false ? true: null);

doesn't?

like image 325
Jokii Avatar asked Jun 07 '13 17:06

Jokii


People also ask

What could be the reason if you are getting NullPointerException?

What Causes NullPointerException. The NullPointerException occurs due to a situation in application code where an uninitialized object is attempted to be accessed or modified. Essentially, this means the object reference does not point anywhere and has a null value.

How do I fix NullPointerException?

In Java, the java. lang. 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.

Why does NullPointerException occur in selenium Webdriver?

NullPointerException is thrown when an application attempts to use null in a case where an object is required. These include: Calling the instance method of a null object. Accessing or modifying the field of a null object.

Is NullPointerException checked or unchecked?

Answer: NullPointerException is not a checked exception. It is a descendant of RuntimeException and is unchecked.


1 Answers

I think what's happening is that ((val == 1) ? true : null) always returns null and it then tries to unbox that into a boolean. That causes a null pointer exception.

After I said this, @JonSkeet marked your question as a duplicate because of NullPointerException in ternary expression with null Long The answer there has a much more detailed explanation.

like image 106
Daniel Kaplan Avatar answered Nov 02 '22 23:11

Daniel Kaplan