Search code examples
javajls

Why does returning null for a primitive work in this case?


This ugly piece of code does compile but throws NPE if s == null

public static boolean isNullOrEmpty(String s)
{
    return s != null ? s.isEmpty() : null;
}

while this does not (as expected):

public static boolean isNullOrEmpty(String s)
{
    if(s != null)
        return s.isEmpty();
    else
        return null;
}

I know both of them are plainly wrong, but as I found the first piece of code in our sources, I was quite surprised it did compile.

Edit: Here's the relevant part of the JLS from Java 7. I guessed the first statement would apply but the bold one does.

15.25 Conditional Operator ? :

[...]

The type of a conditional expression is determined as follows:

[...]

  • If one of the second and third operands is of primitive type T, and the type of the other is the result of applying boxing conversion (§5.1.7) to T, then the type of the conditional expression is T.

[...]

  • Otherwise, the second and third operands are of types S1 and S2 respectively. Let T1 be the type that results from applying boxing conversion to S1, and let T2 be the type that results from applying boxing conversion to S2. The type of the conditional expression is the result of applying capture conversion (§5.1.10) to lub(T1, T2) (§15.12.2.7).

Solution

  • The first has a ternary operator which has a result type of Boolean. The NPE is converting a null to a boolean.

    It is actually something like:

    Boolean temp = s != null ? s.isEmpty() : null; //no problems here
    return temp; //crash when temp==null
    

    The second is trying to return a wrong type (Object instead of primitive) - and thus does not compile.