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