What are Bitwise & Bit Shift Operators in java

You are here : Home / Core Java Tutorials / Core Java tutorial in detail

Bitwise & Bit Shift Operators >

Bitwise operators can be applied on byte, short, char, int and long.
Bitwise operator performs operations on bits.





Bitwise Operators
&
bitwise AND operator

operator1
operator2
bitwise AND operator
Result
0
0
0
0
1
0
1
0
0
1
1
1

^
bitwise EXCLUSIVE OR operator (XOR)

operator1
operator2
bitwise EXCLUSIVE OR
Result
0
0
0
0
1
1
1
0
1
1
1
0

|
bitwise INCLUSIVE OR operator

operator1
operator2
bitwise INCLUSIVE OR
Result
0
0
0
0
1
1
1
0
1
1
1
1

~
unary bitwise complement operator

Inverts the bits

operator
unary bitwise complement operator
Result
0
1
1
0




Bitshift Operators
<<
bitwise Left Shift Operator
Moves specified bits to left.
>>
bitwise Right Shift Operator
Moves specified bits to right.
>>>
unsigned Right Shift Operator
shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension


Program 4.1 to demonstrate Bitwise operators
/** JavaMadeSoEasy.com */
public class BitWiseOperatorTest {
   public static void main(String[] args) {
         
          int x=38; //0010 0110
          int y=58; //0011 1010
          System.out.println(x+" - "+Integer.toBinaryString(x));
          System.out.println(y+" - "+Integer.toBinaryString(y));
          int z=x&y;
          System.out.println("\n & operator");
          System.out.println(z+" - "+Integer.toBinaryString(z));
          z=x^y;
          System.out.println("\n ^ operator");
          System.out.println(z+" -  "+Integer.toBinaryString(z));
          z=x|y;
          System.out.println("\n | operator");
          System.out.println(z+" - "+Integer.toBinaryString(z));
         
         
   }
}
/*OUTPUT
38 - 100110
58 - 111010
& operator
34 - 100010
^ operator
28 -  11100
| operator
62 - 111110
*/


Program 4.2 to demonstrate Bitshift operators
/** JavaMadeSoEasy.com */
public class BitShiftOperatorTest {
   public static void main(String[] args) {
          //128,64,32,16,   8,4,2,1
          int x=38; //0010 0110
          System.out.println(x+" - "+Integer.toBinaryString(x));
          int z=x>>2;
          System.out.println("\n >> operator");
          System.out.println(z+" -  "+Integer.toBinaryString(z));
          z=x<<2;
          System.out.println("\n << operator");
          System.out.println(z+" - "+Integer.toBinaryString(z));
          x=38;
          z=x>>>2;
          System.out.println("\n >>> operator");
          System.out.println(z+" - "+Integer.toBinaryString(z));
         
         
   }
}
/*OUTPUT
38 - 100110
>> operator
9 -  1001
<< operator
152 - 10011000
>>> operator
9 - 1001
*/

eEdit
Must read for you :