Search code examples
javabooleanshort-circuiting

Multiple logical expressions in one if statement in java


Hi I have this example:

  (1)
  if(false && false ||true){
            System.out.println("a");
  }

result:

a

and

  (2)
  if(false && false | true){
            System.out.println("a");
  }

result:

(empty)

In case (1) we have short-circuit OR , but in the second we have long-circuit OR. From where comes the difference in the behavior? I know that the expression is evaluated from left to right and AND have bigger priority than OR, so I can't figure out why this happens in case 2?


Solution

  • (1)

    if (false && false || true) {
        System.out.println("a");
    }
    

    Here && has higher precedence than ||

    1. false && false gets evaluated first resulting false.
    2. false || true gets evaluated resulting true.

    So the result outputs "a".

    (2)

    if (false && false | true) {
        System.out.println("a");
    }
    

    Here | has higher precedence than &&

    1. false | true gets evaluated first resulting true.
    2. false && true gets evaluated resulting false.

    So nothing is output.

    Hope it makes sense