Java order of OR comparison

一曲冷凌霜 提交于 2020-01-02 06:23:09

问题


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 should 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


回答1:


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("")) {
        // ...
    }
}



回答2:


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




回答3:


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?]




回答4:


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




回答5:


try that with if(!"".equals(someString)) which enables to avoid an explicit null-check




回答6:


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.



来源:https://stackoverflow.com/questions/6426201/java-order-of-or-comparison

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!