File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Conditional Operators Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Conditional Operators" Watch "Conditional Operators" New topic

Conditional Operators

Anu Rastogi

Joined: Jan 08, 2007
Posts: 3
Check out this piece of code:
public class BooleanTest1{
public static void main(String args[])
boolean a = false;
boolean b = false;
boolean c = false;
boolean d = (a=true) || (b=true) && (c=true);


The result is a=true;b=false;c=false

I understand that if the first operand of || operator is evaluated to true, the second operand is not evaluated.
But the precedence of && is greater than ||. In this case, shouldn't (b=true) && (c=true) be evaluated before the operand for || is evaluated?
Ajay Singh
Ranch Hand

Joined: Dec 13, 2006
Posts: 182
&& gets higher precedence and its evaluated left-to-right so, the left side will be evaluated first. so, (a=true)||(b=true) is
Joel Jorgensen

Joined: Oct 13, 2006
Posts: 22
I think this happens because && and || are "short circuit" operators, so the JVM takes the path that will allow it to resolve the expression the fastest. The reasoning may sound a little backwards, but I'll do my best to keep it straightforward:

JVM sees (a = true) || (b = true) && (c = true)
JVM recognizes && has higher precedence, so re-groups expression like this: (a = true) || ( (b = true) && (c = true) )
JVM realizes that if first operand (a = true) is true it can skip everything else, so it checks that first. It turns out that it is true, so JVM skips the evaluation of the remaining operands since (as far JVM is concerned) they would have no impact on the outcome and evaluating them would be a waste of cycles.

So for short-circuit operators the precedence of && means that ((b = true) && (c = true)) will be evaluated as the right-side operand of the || if it is needed to determine the outcome, not first.

In the same vein, if you had the following code:

The final values would be
a: false
b: false
c: false

Even though the parenthesis on the right side have higher precedence than && their contents won't be evaluated because they don't need to be.

I hope that helps, but if you'd like me to clarify something I said here (or if I got something dead wrong!) please let me know

Go is to the fountain.
Anu Rastogi

Joined: Jan 08, 2007
Posts: 3
Thanks Joel!!
That explanation makes a lot of sense
I agree. Here's the link:
subject: Conditional Operators
It's not a secret anymore!