No announcement
 

Bitwise Operators

Bitwise operator works directly on the bits of an integer value.

  1. Bitwise AND, &
    It returns bit by bit AND of input values, i.e., if both bits are 1, it gives 1, else it shows 0.
  2. Bitwise OR, |
    It returns bit by bit OR of input values, i.e., if either of the bits is 1, it gives 1, else it shows 0.
  3. Bitwise XOR, ^
    It returns bit by bit XOR of input values, i.e., if corresponding bits are different, it gives 1, else it shows 0.
  4. Bitwise Compliment, ~
    It returns one’s complement representation of the input value, i.e., with all bits inverted (makes every 0 to 1, and every 1 to 0).
  5. Shift Left, <<
    It moves all bits by a given number of bits to the left.
  6. Shift Right, >>
    It moves all bits by a given number of bits to the right.
  7. Zero Fill Shift Right, >>>
    Same as right shift, But the vacant leftmost position is filled with 0 instead of the sign bit.

Example:

BitwiseOperatorsDemo.java

package com.codingnous.tutorial;

public class BitwiseOperatorsDemo {

	public static void main(String[] args) {

		// Two variable for performing operations.
		int a = 4, b = 5;

		// Bitwise AND
		System.out.println(a + " & " + b + " = " + (a & b));

		// Bitwise OR
		System.out.println(a + " | " + b + " = " + (a | b));

		// Bitwise XOR
		System.out.println(a + " ^ " + b + " = " + (a ^ b));

		// Bitwise Compliment
		System.out.println("~" + a + " = " + (~a));

		// 2 Bit left shift operation
		System.out.println(a + " << 2 = " + (a << 2));

		// 2 Bit right shift operation
		System.out.println(b + " >> 2 = " + (a >> 2));

		// 2 Bit right shift fill zero operation
		System.out.println(a + " >>> 2 = " + (a >>> 2));
	}

}

Output
4 & 5 = 4 4 | 5 = 5 4 ^ 5 = 1 ~4 = -5 4 << 2 = 16 5 >> 2 = 1 4 >>> 2 = 1