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:
[...]
[...]
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.