Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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??
like image 200
Hard Avatar asked Feb 09 '23 02:02

Hard


2 Answers

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.

like image 129
Tim Biegeleisen Avatar answered Apr 13 '23 01:04

Tim Biegeleisen


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
like image 31
Ryan Avatar answered Apr 13 '23 00:04

Ryan