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?
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.
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.
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.
Answer: NullPointerException is not a checked exception. It is a descendant of RuntimeException and is unchecked.
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.
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