d1ck50n
d1ck50n

Reputation: 1331

logical OR operator vs bitwise OR operator

does anyone know why:

if (false && true || true) {
       System.out.println("True");
} else {
      System.out.println("False");
}

Print "True"

if (false && true | true) {
           System.out.println("True");
    } else {
          System.out.println("False");
    }

Print "False"

Upvotes: 16

Views: 5029

Answers (2)

Faisal Feroz
Faisal Feroz

Reputation: 12785

In the first case && has higher precedence than || operator so the expression is evaluated as if ( (false && true) || true ) and you get True.

In the second case bitwise OR operator has higher precedence than && so the expression is evaluated as if ( false && ( true | true ) ) and you get False.

Upvotes: 21

T.J. Crowder
T.J. Crowder

Reputation: 1074168

Because of operator precedence. In your first example, the && is done first, and then the ||. But the bitwise OR has higher precedence, so in your second example the | is done first, then the &&.

Upvotes: 18

Related Questions