&&(AND) 和 ||(OR) 在 IF 语句中 [英] && (AND) and || (OR) in IF statements

查看:40
本文介绍了&&(AND) 和 ||(OR) 在 IF 语句中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

if(!partialHits.get(req_nr).containsKey(z) || partialHits.get(req_nr).get(z) < tmpmap.get(z)){  
    partialHits.get(z).put(z, tmpmap.get(z));  
}

其中 partialHits 是一个 HashMap.
如果第一条语句为真,会发生什么? Java 还会检查第二条语句吗? 因为为了使第一条语句为真,HashMap 不应该包含给定的键,所以如果检查第二个语句,我将得到 NullPointerException.
所以简单来说,如果我们有以下代码

where partialHits is a HashMap.
What will happen if the first statement is true? Will Java still check the second statement? Because in order the first statement to be true, the HashMap should not contain the given key, so if the second statement is checked, I will get NullPointerException.
So in simple words, if we have the following code

if(a && b)  
if(a || b)

Java 会检查 b 是否在第一种情况下 a 为假,如果 a 在第二种情况下为真?

would Java check b if a is false in the first case and if a is true in the second case?

推荐答案

不,它不会被评估.这是非常有用的.比如你需要测试一个String是否为null或空,可以这样写:

No, it will not be evaluated. And this is very useful. For example, if you need to test whether a String is not null or empty, you can write:

if (str != null && !str.isEmpty()) {
  doSomethingWith(str.charAt(0));
}

或者反过来

if (str == null || str.isEmpty()) {
  complainAboutUnusableString();
} else {
  doSomethingWith(str.charAt(0));
}

如果我们在 Java 中没有短路",我们会在上面的代码行中收到很多 NullPointerExceptions.

If we didn't have 'short-circuits' in Java, we'd receive a lot of NullPointerExceptions in the above lines of code.

这篇关于&amp;&amp;(AND) 和 ||(OR) 在 IF 语句中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆