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).