1

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 (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? 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?

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?

Nubcake
  • 449
  • 1
  • 8
  • 21
  • 1
    Note that it is nothing to do with while-loop behavior. The rules for evaluating `&&` are the same for an if condition, assignment of the result to a boolean variable, etc. – Patricia Shanahan Mar 08 '15 at 15:58

2 Answers2

4

&& 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.

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.

SMA
  • 36,381
  • 8
  • 49
  • 73
  • Wow, I did not know this; I thought all this time that conditions were to be evaluted as whole. – Nubcake Mar 08 '15 at 15:55
0
 (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

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
Community
  • 1
  • 1
Paul John
  • 1,626
  • 1
  • 13
  • 15