Reputation: 469
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?
Upvotes: 1
Views: 2251
Reputation: 1661
(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
Upvotes: 0
Reputation: 37083
&&
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.
Upvotes: 4