does the following snippet throw NPE when argument is null?
public void doSomething(String string) {
if (string.trim().equals("") || string==null) {
[...]
}
}
I've found this in someone else's code (someone else who should be more experienced than me). Since I've been facing difficulties with this code, I want to ask if the comparison 开发者_如何学JAVAshould be inverted or the Java compiler is someway smart enough to swap the operands. I don't have direct control over this code, nor this throws me NPE because of many catch blocks.
Thank you
Yes. That snippet of code will throw a NullPointerException
when string
is null
. Changing it to the following is advisable:
public void doSomething(String string) {
if (string==null || string.trim().equals("")) {
// ...
}
}
It will throw a NullPointerException
because if string
is null and you try to trim a null
it will throw the exception. Try putting the null check before you try to trim().
Yeah, that looks dodgy to me. It should almost certainly be the other way round. Java logical operators (like in C and C++) have a "short-circuit" facility, whereby the left-hand operand is evaluated first, and then the right-hand operand is only evaluated if needed.
[Note: Couldn't you have just tried running this to find out whether it throws an exception?]
Yes, every sensible IDE will complain about this code, because the right half can never be evaluated.
if (string.trim().equals("") || string==null) {
if the string is null, the left part throws a NPE, so the right part never gets evaluated
try that with if(!"".equals(someString))
which enables to avoid an explicit null-check
binary operators of equal precedence are always evaluated from left to right, apart from assignment (in just about every language I can think of) This is important in this case, because ||
is a short cut operator. If the result is know i.e. the first expression is true, the second expression will not be evaluated. So the correct way to use ||
and &&
to check for null is like the following.
if(text == null || text.method())
or
if(text != null && text.method2())
The order is this way as we read left to right (and top to bottom) in English. c.f. In Japanese you read from top to bottom then right to left.
精彩评论