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
Yes. That snippet of code will throw a
NullPointerExceptionwhenstringisnull. Changing it to the following is advisable: