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?