Possible Duplicate:
NullPointerException through auto-boxing-behavior of Java ternary operator
The following code uses simple conditional operators.
public class Main
{
public static void main(String[] args)
{
Integer exp1 = true ? null : 5;
Integer exp2 = true ? null : true ? null : 50;
System.out.println("exp1 = " +exp1+" exp2 = "+exp2);
Integer exp3 = false ? 5 : true ? null: 50; //Causes the NullPointerException to be thrown.
System.out.println("exp3 = "+exp3);
}
}
This code compiles fine. All the expressions ultimately attempt to assign null
to Integer
type variables exp1
, exp2
and exp3
respectively.
The first two cases don't throw any exception and produce exp1 = null exp2 = null
which is obvious.
The last case however, if you go through it carefully, you will see it also attempts to assign null
to Integer
type variable exp3
and looks something similar to the preceding two cases but it causes the NulllPointerException
to be thrown. Why does it happen?
Before I posted my question, I have referred to this nice question but in this case, I couldn't find what rules as specified by JLS are applied here.
The NullPointerException can be avoided using checks and preventive techniques like the following: Making sure an object is initialized properly by adding a null check before referencing its methods or properties. Using Apache Commons StringUtils for String operations e.g. using StringUtils.
NullPointerException is a runtime exception and it is thrown when the application try to use an object reference which has a null value. For example, using a method on a null reference.
NullPointerException is thrown when an application attempts to use an object reference that has the null value. These include: Calling an instance method on the object referred by a null reference. Accessing or modifying an instance field of the object referred by a null reference.
The null
is being unboxed to an int
, because the assignment is due to the 5
an int
, not an Integer
. However, a null
cannot be represented as an int
, hence the NullPointerException
.
If you replace 5
by new Integer(5)
, then it'll work.
Integer exp3 = false ? new Integer(5) : true ? null : 50;
? :
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