Java : Bitwise Logical Operators

Java supports several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte. These Bitwise operator works on bits and performs the bit-by-bit operation.

For Example: Assume if a = 60 and b = 13; now in the binary format they will define follows:


a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011

See Also :

Here is a complete list of bitwise operators:

Operator Result
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
>> Shift right
>>> Shift right zero fill
<< Shift left
&= Bitwise AND assignment
|= Bitwise OR assignment
^= Bitwise exclusive OR assignment
>> Shift right assignment
>>>= Shift right zero-fill assignment
<<= Shift left assignment

Bitwise Logical Operators:

Here is a table of the result after performing a bitwise operator on values A  and B.

A B A | B A & B A ^ B ~A
0 0 0 0 0 1
1 0 1 0 1 0
0 1 1 0 1 1
1 1 1 1 0 0

Bitwise Operator Example

public class BitwiseOperatorTest {

	public static void main(String[] args) {
		//Bitwise And
	 System.out.println(9 &amp; 7);

	 //Bitwise or
	 System.out.println(19 | 7);

	 //Bitwise XOR
	 System.out.println(9 ^ 7);

	 //left Shift
	 System.out.println(9 &lt;&lt; 7);

	 //Bitwise complement(~), Inverts ones and zeros in a number

	 int i = 1;
	    System.out.println(i);

	    int j = ~i + 1;
	    System.out.println(j);

	    i = ~j + 1;
	    System.out.println(i);

	    //Example Bitwise demonstration
	    String binary[] = {
	    	      &quot;0000&quot;, &quot;0001&quot;, &quot;0010&quot;, &quot;0011&quot;, &quot;0100&quot;, &quot;0101&quot;, &quot;0110&quot;, &quot;0111&quot;,
	    	      &quot;1000&quot;, &quot;1001&quot;, &quot;1010&quot;, &quot;1011&quot;, &quot;1100&quot;, &quot;1101&quot;, &quot;1110&quot;, &quot;1111&quot;
		    	    };
    int a = 3; // 0 + 2 + 1 or 0011 in binary
    int b = 6; // 4 + 2 + 0 or 0110 in binary
    int c = a | b;
    int d = a &amp; b;
    int e = a ^ b;
    int f = (~a &amp; b) | (a &amp; ~b);
    int g = ~a &amp; 0x0f;

    System.out.println(&quot;        a = &quot; + binary[a]);
    System.out.println(&quot;        b = &quot; + binary[b]);
    System.out.println(&quot;      a|b = &quot; + binary);
    System.out.println(&quot;      a&amp;b = &quot; + binary[d]);
    System.out.println(&quot;      a^b = &quot; + binary[e]);
    System.out.println(&quot;~a&amp;b|a&amp;~b = &quot; + binary[f]);
    System.out.println(&quot;       ~a = &quot; + binary[g]);
	}
}

Output


1
23
14
1152
1
-1
1
        a = 0011
        b = 0110
      a|b = 0111
      a&b = 0010
      a^b = 0101
~a&b|a&~b = 0101
       ~a = 1100