Java logical operator (&&, ||) short-circuit mechanism

后端 未结 6 2054
野的像风
野的像风 2021-02-19 06:28

As I was reading a colleague\'s Java code, I stumbled upon an army of if/else statements. In these statements, several && and || operators wer

6条回答
  •  忘掉有多难
    2021-02-19 06:45

    It's simply because

    if (false && true || true)
    

    is equivalent to (&& has a higher precedence)

    if ((false && true) || true)
    

    which is

    if (false || true)
    

    which is... true.

    Note: In the expression true || true && false, the part true && false is called a dead code because it doesn't affect the final result of the evaluation, since true || anything is always true.


    It is worth mentioning that there exist & and | operators that can be applied to booleans, they are much like && and || except that they don't short circuit, meaning that if you have the following expression:

    if (someMethod() & anotherMethod())
    

    and someMethod returns false, anotherMethod will still be reached! But the if won't be executed because the final result will be evaluated to false.

提交回复
热议问题