Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

logical OR operator vs bitwise OR operator

Tags:

java

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"

like image 884
d1ck50n Avatar asked Sep 13 '10 08:09

d1ck50n


People also ask

What is the difference between bitwise and logical?

The key difference between Bitwise and Logical operators is that Bitwise operators work on bits and perform bit by bit operations while logical operators are used to make a decision based on multiple conditions.

Is bitwise or faster than logical or?

No. First, using bitwise operators in contrast to logical operators is prone to error (e.g., doing a right-shift by 1 is NOT equivalent to multiplying by two). Second, the performance benefit is negligible (if any).

What is the difference between logical or and logical AND?

Both of them combine Boolean values ( true/false values ) into one Boolean value. But each does this in a different way: All the values AND combines must be true to get a true. At least one of the values OR combines must be true to get a true.

What is the difference between bitwise not and logical not?

“Logical not or !” is meant for boolean values and “bitwise not or ~” is for integers. Languages like C/C++ and python do auto promotion of boolean to integer type when an integer operator is applied. But Java doesn't do it.


1 Answers

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.

like image 157
Faisal Feroz Avatar answered Sep 27 '22 21:09

Faisal Feroz