class test {
public static void main (String[] args) {
boolean a = false;
boolean b = true;
if (a && a || b) {
System.out.println(true);
}
}
} //--why it always true????o/p is true but why??
Order of operations.
&&
has higher precedence than ||
and therefore is evaluated first. Your if
condition can be rewritten as follows:
(a && a) || b
(false && false) || true
false || true
true
This condition will always be false || true
which is always true
for the conditions you listed.
Check here for an official table from Oracle which lists the precedence of all operators.
Your code has the equivalence to this statement ::
If A is true or B is true the statement is true
Since B is set to true your statement is true. Also, there is no need to test A twice so instead of doing
(a && a || b) // old
(a || b) //new
&&
has a higher order of operation then ||
so it is evaluated first.
To work around this you can use braces
if( a && ( a || b )) //tests as i believe you wanted although its redundent
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With