Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

java - &&(AND)和|| (OR)在IF语句中(&& (AND) and || (OR) in IF statements)

I have the following code:

(我有以下代码:)

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

where partialHits is a HashMap.

(其中partialHits是一个HashMap。)
What will happen if the first statement is true?

(如果第一个陈述为真会怎样?)

Will Java still check the second statement?

(Java还会检查第二条语句吗?)

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 .

(因为为了使第一条语句为真,所以HashMap不应包含给定的键,因此,如果选中第二条语句,则将获得NullPointerException 。)
So in simple words, if we have the following code

(简单来说,如果我们有以下代码)

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

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

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

  ask by Azimuth translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

(例如,如果您需要测试String是否为null或为空,则可以编写:)

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

or, the other way around

(或者,反过来)

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

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

(如果我们在Java中没有“短路”,那么在上面的代码行中将会收到很多NullPointerExceptions。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...