Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java order of OR comparison

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

like image 218
usr-local-ΕΨΗΕΛΩΝ Avatar asked Nov 28 '22 12:11

usr-local-ΕΨΗΕΛΩΝ


2 Answers

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("")) {
        // ...
    }
}
like image 53
Asaph Avatar answered Nov 30 '22 00:11

Asaph


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

like image 20
RMT Avatar answered Nov 30 '22 00:11

RMT