简体   繁体   English

while循环条件评估

[英]while loop condition evaluation

I have a snippet of code that involves two conditions to enter a while loop but I am confused from the output and expected result from the following code: 我有一段涉及两个条件的代码片段,它们进入while循环,但是我对以下代码的输出和预期结果感到困惑:

while (curr != null && key.compareTo(curr.getKey()) > 0) {
  prev = curr;
  curr = prev.getNext();
  if (curr == null) {
    System.out.println(curr + " is null");
  }
}

When I ran this code , I expected it to throw a null pointer exception ,since curr is null and I'm calling a method on null, after the message is printed out, however it exits the loop normally and I was wondering whether this is normal behavior? 当我运行这段代码时,我期望它会抛出一个空指针异常,因为curr为null,并且在消息打印出来后我正在对null调用一个方法,但是它正常退出了循环,我想知道这是否是正常行为? From here it seems that it does evaluate one condition at a time but I thought while loops evaluate everything inside the bracket in one boolean expression? 从这里看来,它一次只评估一个条件,但是我认为while循环用一个布尔表达式评估括号内的所有内容?

I ran one test where I swapped the operands for && the other way around and found that it does throw a null pointer exception then! 我进行了一个测试,以另一种方式交换了&&的操作数,然后发现它确实引发了空指针异常! What is the reason for this? 这是什么原因呢?

Q. Does the while loop condition get evaluated as a whole or does it evaluate one condition at a time before deciding whether to enter the loop? 问:while循环条件是整体评估还是在决定是否进入循环之前一次评估一个条件?

&& is a short circuit (or short hand) operator. &&是短路(或短手)运算符。 It will evaluate first condition and if condition is true then only will evaluate second condition. 它将评估第一个条件,如果条件为真,则仅评估第二个条件。

So if my condition is conditon1 && condition2 , it will evaluate condition2 if and only if condition1 is true. 因此,如果我的条件是conditon1 && condition2 ,则当且仅当condition1为true时,它将评估condition2。

So in your case, it will evaluate not null condition ( curr != null ) and if it fails then it wont evaluate the other one and hence no NullPointerException and hence you see while loop exiting gracefully. 因此,在您的情况下,它将评估不为空的条件( curr != null ),如果失败,则将不评估另一个条件,因此也不会评估NullPointerException,因此您会看到while循环正常退出。

 (curr != null && key.compareTo(curr.getKey()) 

&& ensures that left is true before running the right &&确保在运行右之前左为真

The && and || &&和|| operators "short-circuit", meaning they don't evaluate the right hand side if it isn't necessary. 操作员“短路”,这意味着如果不需要,他们不会评估右侧。

The & and | &和| operators, when used as logical operators, always evaluate both sides. 运算符用作逻辑运算符时,始终会评估双方。

Here is a really good explanation of this Java logical operator short-circuiting 这是对Java逻辑运算符短路的一个很好的解释

There is only one case of short-circuiting for each operator, and they are: 每个操作员只有一种短路情况,它们是:

 false && ... - it is not necessary to know what the right hand side is, the result must be false true || ... - it is not necessary to know what the right hand side is, the result must be true 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM