Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Conditional Operators

 
Anu Rastogi
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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);
System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("c="+c);
}

}

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
Posts: 182
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
&& gets higher precedence and its evaluated left-to-right so, the left side will be evaluated first. so, (a=true)||(b=true) is
evaluated.
 
Joel Jorgensen
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Anu Rastogi
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Joel!!
That explanation makes a lot of sense
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic