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

short circuit operators precedence

 
preeti khane
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
try this discussion:
operator precedence && and ||
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
welcome to the Ranch Mario.
 
Sefa Urgenc
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To answer your question Sefa, between &,^,|,
Hieghest precedence : &
Next: ^
Least:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic