Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Operators Precedance: Output of the Program

 
Chandrakanth
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can you pls, tell me how is the output of this prog is true false false.

my understanding is this:
() have higher precedance than || and && so all of the () operators should be evaluated?
so abc will get the value of true.
than only short circuit operators should be applied...

class EBH202 {
static boolean a, b, c;
public static void main (String[] args) {
boolean x = (a = true) || (b = true) && (c = true);
System.out.print(a + "," + b + "," + c);
}
}
 
rey anz
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
|| and && are shortcircuit operaters hence after evaluating (a=true) no (..) are evaluated and as a, b and c had been initialized to false, so the output is true false false which are the values for a, b and c respectively.
 
Anindo Ghosh
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
boolean x = (a = true) || (b = true) && (c = true);

Since && has a higher precedence than the || operator,
the expression evaluates to

boolean x = (a = true) || ( (b = true) && (c = true) );

Now the *short-circuit* operators come into play.
As soon as (a=true) evaluates to true, the runtime abandons the evaluation of the rest of the expression.
 
Chaitanya Varanasi
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
The output which it shows is absolutely right, because if you have seen the condition , the conditional Operator is short-circuited OR operator.
So While evaluating the Expression, the Short-circuted OR will look if the first operand is true or not.. If its true, then it doesnt try to execute the other part of the expression, which is the reason why the values of A,B,C will retain the default values.

Hope you have got the answer,
Cheers
 
Chandrakanth
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thx for the reply,
 
Naresh Gunda
Ranch Hand
Posts: 163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
boolean x = (a = true) || (b = true) && (c = true);

here && operator is having highest precedence, so the expression (b=true) should be evaluated first, since it is short circuted operator (c-true) will be ignored.
then the expression will be
boolean x = (a=true) || true //c=true is not evauated hence c is false

can u pls tell me why b is false in the output
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic