| Author |
Is order of conditional evalution garanteed?
|
Derik Davenport
Ranch Hand
Joined: May 30, 2011
Posts: 52
|
|
Is there any garantee in java about the order of boolean evaluation for the AND statement?
Let me clarify my meaning. Consider the following code
In C, if condition 1 is false, the condition 2 will not be evaluated.
Consider the following Java example
In Java was like C, then if myObject == null, then I can be assured that the second condition will never be evaluated and thus it would be impossible for a NullPointerException to be thrown. I also know that the variable j will not have been incremented. Does this kind of logic hold for Java? Or does it depend on the implementation of the JVM?
|
 |
Paul Clapham
Bartender
Joined: Oct 14, 2005
Posts: 16483
|
|
|
It's documented in the Java Language Specification that it should work that way.
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32694
|
|
You need to be very careful about combining && (or ||) with side-effects like j++.
To elaborate on what you have already been told, I checked in the Java Language Specification for && (|| follows in the next section), and you now have the link to the actual page. And, good grief, I can actually understand that page of the JLS!
|
 |
Matthew Brown
Bartender
Joined: Apr 06, 2010
Posts: 3793
|
|
|
The other thing you can use, if you really want to confuse people, are the non-shortcircuiting boolean operators | and &. Then both conditions will be evaluated.
|
 |
 |
|
|
subject: Is order of conditional evalution garanteed?
|
|
|