Java Bitwise Operators Logical Operators

Introduction

The bitwise logical operators are &, |, ^, and ~.

The following table shows the outcome of each operation.

A B A | BA & B A ^ B~A
0 0 00 0 1
1 0 10 1 0
0 1 10 1 1
1 1 11 0 0

Bitwise NOT

Bitwise NOT is also called the bitwise complement.

The unary NOT operator ~ inverts all of the bits of its operand.

For example, the number 42, which has the following bit pattern:

00101010 

becomes

11010101 

after the NOT operator is applied.

Bitwise AND

The AND operator & produces a 1 bit if both operands are also 1.

A zero is yielded for all other cases. Here is an example:

42 and 15

 00101010    42 
&00001111    15  
---------------
 00001010    10 

Bitwise OR

The OR operator | returns 1 if either of the bits in the operands is a 1,

or operation:
 00101010    42 
|00001111    15 
-------------------
 00101111    47 

Bitwise XOR

The XOR operator ^ returns 1 if exactly one operand is 1.

Otherwise, the result is zero.

The following example shows the effect of the ^.

  00101010    42 
^ 00001111    15 
----------------
  00100101    37 
// Demonstrate the bitwise logical operators.
public class Main {
  public static void main(String args[]) {
    String binary[] = {/*from  w w  w.  j a  v a2 s.com*/
      "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111",
      "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"
    };
    int a = 3; // 0 + 2 + 1 or 0011 in binary
    int b = 6; // 4 + 2 + 0 or 0110 in binary
    int c = a | b;
    int d = a & b;
    int e = a ^ b;
    int f = (~a & b) | (a & ~b);
    int g = ~a & 0x0f;

    System.out.println("        a = " + binary[a]);
    System.out.println("        b = " + binary[b]);
    System.out.println("      a|b = " + binary[c]);
    System.out.println("      a&b = " + binary[d]);
    System.out.println("      a^b = " + binary[e]);
    System.out.println("~a&b|a&~b = " + binary[f]);
    System.out.println("       ~a = " + binary[g]);
  }
}



PreviousNext

Related