num1 | num2 compares corresponding bits of num1 and num2 and generates 1 if either bit is 1, else it returns 0. In our case it would return 31 which is 00011111
num1 ^ num2 compares corresponding bits of num1 and num2 and generates 1 if they are not equal, else it returns 0. In our example it would return 29 which is equivalent to 00011101
~num1 is a complement operator that just changes the bit from 0 to 1 and 1 to 0. In our example it would return -12 which is signed 8 bit equivalent to 11110100
num1 << 2 is left shift operator that moves the bits to the left, discards the far left bit, and assigns the rightmost bit a value of 0. In our case output is 44 which is equivalent to 00101100
Note: In the example below we are providing 2 at the right side of this shift operator that is the reason bits are moving two places to the left side. We can change this number and bits would be moved by the number of bits specified on the right side of the operator. Same applies to the right side operator.
num1 >> 2 is right shift operator that moves the bits to the right, discards the far right bit, and assigns the leftmost bit a value of 0. In our case output is 2 which is equivalent to 00000010
result = ~num1;
System.out.println("~num1: "+result);
result = num1 << 2;
System.out.println("num1 << 2: "+result);
result = num1 >> 2;
System.out.println("num1 >> 2: "+result); |
Example of Bitwise Operators  |
public class BitwiseOperatorDemo
{
public static void main(String args[])
{
int num1=11,num2=22; /*11=00001011, 22=00010110*/
int result = 0;
result = num1 & num2;
System.out.println("num1 & num2: "+result);
result = num1 | num2;
System.out.println("num1 | num2: "+result);
result=num1^num2;
System.out.println("num1^num2:"+result);
|
Output: num1 & num2: 2 |
num1 | num2: 31
num1 ^ num2: 29
~num1: -12 num1<<2:44num1>>2:2