Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional operators in Java throw an unexpected NullPointerException [duplicate]

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.

like image 743
Tiny Avatar asked Oct 17 '12 15:10

Tiny


People also ask

How do I fix NullPointerException in Java?

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.

What is NullPointerException in Java example?

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.

When should we throw a NullPointerException?

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.


1 Answers

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;

See also:

  • Java Language Specification - Chapter 15.25 - Conditional Operator ? :
  • Booleans, conditional operators and autoboxing
like image 80
BalusC Avatar answered Oct 25 '22 11:10

BalusC