Java conditional statement, why the following code gives 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??
+4
source share
5 answers

The order of operations.

&&has a higher priority than ||, and therefore is evaluated first. Your condition ifcan be rewritten as follows:

(a && a) || b
(false && false) || true
false || true
true

This condition will always be false || true, which is always truefor the conditions you have listed.

Check here for the official table from Oracle, which lists the priorities of all operators.

+7
source

Your code has the equivalence of this statement:

If A is true or B is true, the statement is true

B true, . , A,

(a && a || b) // old 
(a || b) //new

&& , ||, . ,

if( a && ( a || b )) //tests as i believe you wanted although its redundent
+1
a && a || b :
    a && a => false && false => false
    false || b => false || true => true

:

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

.

: , parens, .

0

A = False
B = True

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

False || True = True

0

, AND (&) , OR (||).

  if (b||a&&a) {

        System.out.println(true);
    }

, && .

0

Source: https://habr.com/ru/post/1623511/


All Articles