OR比较的Java顺序 [英] Java order of OR comparison
问题描述
当参数为null时,以下代码片段会抛出NPE吗?
does the following snippet throw NPE when argument is null?
public void doSomething(String string) {
if (string.trim().equals("") || string==null) {
[...]
}
}
我在别人的代码中找到了这个(其他人应该比我更有经验)。由于我一直面临着这段代码的困难,我想问一下比较是否应该反转,或者Java编译器是否足够聪明以交换操作数。我没有直接控制这个代码,也没有因为许多catch块而抛出NPE。
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.
谢谢
推荐答案
是的。当 string
null
NullPointerException >。建议将其更改为以下内容:
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("")) {
// ...
}
}
这篇关于OR比较的Java顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!