&安培;&安培; (AND)和|| (或)在IF声明中 [英] && (AND) and || (OR) in IF statements

查看:116
本文介绍了&安培;&安培; (AND)和|| (或)在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)

如果 a b $ c>在第一种情况下是假的,如果在第二种情况下 a 为真?

推荐答案

不,它不会被评估。这非常有用。例如,如果您需要测试String是否为空或空,您可以写:

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中的短路,我们' d在上面的代码行中收到很多NullPointerExceptions。

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

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

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