简体   繁体   中英

java conditional operator,why following code is giving output as true?

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 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
a && a || b :
    a && a => false && false => false
    false || b => false || true => true

If there had been parens to change the operator precedence:

a && (a||b) :
    a || b => false || true => true
    a && true => false && true => false

then the result would be different.

Moral: if you are unsure of the precedence use parens so you are sure.

A = False
B = True

A && A (False && False) = False
( A && A(False) ) || B (True) = True

Your last expression is False || True = True False || True = True

This is because the AND(&&) operator is solved first then the OR(||) operator. run

  if (b||a&&a) {

        System.out.println(true);
    }

it will give you true again because && is calculated first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM