Win a copy of Kotlin in Action this week in the Kotlin forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# short circuit operators precedence

preeti khane
Ranch Hand
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
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
Posts: 2120
try this discussion:
operator precedence && and ||

Anonymous
Ranch Hand
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
Posts: 2120
welcome to the Ranch Mario.

Sefa Urgenc
Ranch Hand
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
Posts: 102