The below table gives the description of the bitwise operators.
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);
}
}
OUTPUTa & b = 4
a | b = 61
a ^ b = 57
~a = -53
a << 2 = 208
a >> 2 = 13
a >>> 2 = 13
DESCRIPTIONAt 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)