Reputation: 1819
Postfix operators [] . (parameters) expression++ expression--
Unary prefix operators ++expression --expression +expression -expression ~ !
Unary prefix creation and cast new (type)
Multiplicative * / %
Additive + -
Shift << >> >>>
Relational < <= > >= instanceof
Equality == !=
Bitwise/logical AND &
Bitwise/logical XOR ^
Bitwise/logical OR |
Conditional AND && //here
Conditional OR || //here
Conditional ?:
Assignment = += -= *= /= %= <<= >>= >>>= &= ^= |=
This are the operator precedence s published in kalid A Mughal & Rasmussen book
according to this book &&
has higher precedence than ||
but the following code
if(true&&false||true)
{
System.out.println("yes");
}
this code prints "yes"
. means first executing "||"
is this book wrong? or my interpretation wrong.
Upvotes: 0
Views: 2395
Reputation: 49
The && is evaluated first... but one side of the "or" || is true, so the overall expression evaluates to "true"
if(true&&false||true)
{
System.out.println("yes");
}
Upvotes: 0
Reputation: 961
If you change your representation you can see it much clearer, for example:
if(true || true && false) {
System.out.println("yes");
} else {
System.out.println("no");
}
If &&
takes precedence you have ( true || (true && false) )
this will be true so will print "yes".
If ||
takes precence you will have ( (true || true) && false)
this will be false and will print out "no.
If you run the above code you will see that the result is "yes" and therefore &&
has precendence.
Upvotes: 0
Reputation: 121068
look carefully, as these are short-circuit AND and OR
So the first part :
true&&false // evaluates to false
Then you have :
false || true
the first part is false, BUT the second part could be true (and in fact it is), thus it moves to check the second part, sees that it's true, thus returns true
Upvotes: 0
Reputation: 117675
if(true && false || true)
==> if(false || true)
==> if(true)
.
AND Truth Table:
F & F = F
T & F = F
F & T = F
T & T = T
OR Truth Table:
F | F = F
T | F = T
F | T = T
T | T = T
Upvotes: 0
Reputation: 47994
Your interpretation is wrong
true && false -> false
false || true -> true
It is expected to print "yes"
Upvotes: 0
Reputation: 6432
true && false
=> false
false || true
=> true
Thus there is no issue as the and statement is executing first then the or statement. The expected result of the code is yes
.
Upvotes: 0
Reputation: 512
Your interpretation is off. If we follow the book, your if-statement can be re-written and maintain the same meaning
if( (true && false) || true)
Now it is very easy to see that this does in fact evaluate to true, and therefore print out "yes".
Upvotes: 0
Reputation: 62469
I guess your interpretation is wrong. Since &&
has higher precedence the order of evaluation is
(true && false) || true
which is
false || true -> true
Upvotes: 3