my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes short circuit operators precedence Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "short circuit operators precedence" Watch "short circuit operators precedence" New topic
Author

short circuit operators precedence

preeti khane
Ranch Hand

Joined: Mar 12, 2003
Posts: 93
operator precedence says && is evaluated before ||
In dan 's exams I saw couple questions which had the following code, I am just giving the lines which are relevant.. the code was compilable
...
static boolean a;
static boolean b;
static boolean c;
public static void main(String args[]){
boolean x = (a=true) || (b=true ) && (c=true);
System.out.println(x + " " + a + " " + b + " " + c);
}

In this case should I be evaluating
((b=true) &&(c=true)) first and then evaluate the result with (a=true)
According to Dan's answers apparently, the precedence order is not relevant here and what happens is that it evaluates a=true and stops right there.
x=true
a=true
b= false
c=false

Can somebody throw light on this?
thanks
Jessica Sant
Sheriff

Joined: Oct 17, 2001
Posts: 4313

actually I believe && and || have the SAME precedence so they are evaluated left to right.
**Don't stress too much over order of operations, its not a big topic on the test (there's other stuff you should probably worry about more -- like Threads / Inner Classes and stuff) -- and in real life -- you'll be smart and just use parenthesis to make the precedence obvious**
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
try this discussion:
operator precedence && and ||


SCJP2. Please Indent your code using UBB Code
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Hi .. well my English is my third languaje.... so excuse me if my grammar is not perfect.!
I see that this question is about Short circuit operands... so the first:
x = (a = true) || ....(anything !) always be resolved as true (for the operator ||)
the last variables are initialized with default values (false) and x is true.
well. this is my first POST! in JavaRanch !
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
welcome to the Ranch Mario.
Sefa Urgenc
Ranch Hand

Joined: Jul 25, 2002
Posts: 34
Hi Jessica,
What about & and | are do they have the same precedence, because you said that && and || have same precedence ?
Thanx
Sefa Urgenc
Monisha Talwar
Ranch Hand

Joined: Feb 11, 2003
Posts: 102
To answer your question Sefa, between &,^,|,
Hieghest precedence : &
Next: ^
Least:


Hey! It compiles! Ship it!
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: short circuit operators precedence
 
Similar Threads
Precedence on Short Circuit Operators
Precedence
unprecedented precedence
Dans' Question Doubt
Conditional Operators