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:
[...]
[...]
Java primitive types (such as int , double , or float ) cannot have null values, which you must consider in choosing your result expression and host expression types.
Returning null is often a violation of the fail fast programming principle. The null can appear due to some issue in the application. The issue can even go to production if the developer has not implemented proper exception handling, which can help quickly detect the issue.
In Java, a null value can be assigned to an object reference of any type to indicate that it points to nothing. The compiler assigns null to any uninitialized static and instance members of reference type. In the absence of a constructor, the getArticles() and getName() methods will return a null reference.
Returning null is usually the best idea if you intend to indicate that no data is available. An empty object implies data has been returned, whereas returning null clearly indicates that nothing has been returned.
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.
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