Menu
Topics Index
...
`
Bitwise operators are used when performing operations on the binary values of the integers.

The below table gives the description of the bitwise operators.
Operator Symbol Functionality Example Result
Bitwise complement operator ~ This operator inverts the bits i.e., it changes 0's to 1's and 1's to 0's. ~0 1
Bitwise AND operator & Returns 1 only when both the bits are 1's 42 & 15 10
Bitwise OR operator | Returns 0 only when both the bits are 0's 42 | 15 47
Bitwise XOR operator ^ Returns 1 when both bits are different. 42 ^ 15 37
Right Shift operator n >> p Shifts n to p bits right 60(0011 1100) >> 2 15(1111)
Unsigned Right Shift operator n >>> p Shifts p bits of n to right side and assigns 0's in high - order bits. 215(1111) >>> 4 215(0000 1111)
Left Shift operator n << p Shifts n to p bits left 60(0011 1100) << 2 240(1111 0000)
Notice that there is no Unsigned Left Shift operator in Java.
BitwiseOperatorsDemo
class BitwiseOperatorsDemo
{
    public static void main(String arg[])
    {
        int a = 52; // 52 = 0011 0100
        int b = 13; // 13 = 0000 1101
        int c = 0;
        c = a & b; // 4  = 0000 0100    // LINE A
        System.out.println("a & b = " + c);
        c = a | b; // 61 = 0011 1101    // LINE B
        System.out.println("a | b = " + c);
        c = a ^ b; // 57 = 0011 1001    // LINE C
        System.out.println("a ^ b = " + c);
        c = ~a; // -4 = 1111 1011    // LINE D
        System.out.println("~a = " + c);
        c = a << 2; // 208 = 1101 0000    // LINE E
        System.out.println("a << 2 = " + c);
        c = a >> 2; // 13 = 0000 1101    // LINE F
        System.out.println("a >> 2  = " + c);
        c = a >>> 2; // 13 = 0000 1101 // LINE G
        System.out.println("a >>> 2 = " + c);    
    }
}
OUTPUT

a & b = 4
a | b = 61
a ^ b = 57
~a = -53
a << 2 = 208
a >> 2  = 13
a >>> 2 = 13

DESCRIPTION

At LINE A, performed AND operation between a and b.
At LINE B, performed OR operation between a and b.
At LINE C, performed XOR operation between a and b.
At LINE D, performed Complement operation on a.
At LINE E, performed Left Shift operation on a.
At LINE F, performed Right Shift operation on a.
At LINE G, performed Unsigned Right Shift operation on a.

THINGS TO TRY
  • Change the values of a and b to 16 and 18 in the above shown program and check the output. The output should be
    a & b = 16 (0001 0000)
    a | b = 18 (0001 0010)
    a ^ b = 2 (0010)
    ~a = -17 (1110 1111)
    a << 2 = 64(0100 0000)
    a >> 2 = 4 (0100)
    a >>> 2 = 4 (0100)
  • Place the below code and check the output.
    int a = 16;    /* 16 = 0001 0000 */  
    int b = 18;    /* 18 = 0001 0010 */        
    int c = a <<< 2;    
    System.out.println("a <<< 2 = " + c );
    The above code throws compilation error, since there is no Unsigned Left Shift Operator(<<<) in java.

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App