Java: Bitwise Operator

bitwise operators in java

Operators

Java provides quite a variety of operators which come in handy to the programmer for the manipulation of variables.

The operators in java are as follows:

  • Arithmetic Operators
  • Relational Operators
  • Bitwise Operators
  • Logical Operators
  • Assignment Operators
Here we will learn more about the Bitwise Operators.

Bitwise Operators

Since the operations in the CPU/ arithmetic unit is done in bit-level, the operators to perform bit-level operations are termed as Bitwise operators.

OperatorFunctionalitySyntax
&(Bitwise AND)The result of AND is 1 only if both bits are 1.a & b
|(Bitwise OR)The result of OR is 1 if any of the two bits is 1a | b
^(Bitwise XOR)The result of XOR is 1 if the two bits are different.a ^ b
~(Bitwise Complement)It takes one number and inverts all bits of ita ~ b
<<(Shift left)Left shifts the bits of the first operand, the second operand decides the number of places to shift.a << b
>>(Shift right)Right shifts the bits of the first operand, the second operand decides the number of places to shift.a >> b

Syntax with Example

Run
public class Main { 
    public static void main(String[] args) 
    { 
        int a = 14, b= 20, c= 8, d= -16 ;

        // 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 complement
        System.out.println("~a = " + ~a); 

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

        // left shift operator 
        System.out.println("c<<2 = " + (c << 2)); 

        // right shift operator 
        System.out.println("d>>2 = " + (d >> 2)); 

        // unsigned right shift operator 
        System.out.println("d>>>2 = " + (d >>> 2)); 
    } 
}

Output

a&b = 4
a|b = 30
a^b = 26
~a = -15
a= 4
c<<2 = 32 d>>2 = -4 d>>>2 = 1073741821