In this tutorial you will learn about the Java Bitwise Operators and its application with practical example.
Java Bitwise Operators
Bitwise operators are used to performing the bit-level operations over their operand.
Let A = 60; and B = 13;
Binary equivalent
A = 0011 1100
B = 0000 1101
Operator | Meaning | Example | Description |
---|---|---|---|
& | Binary AND | (A & B) | It returns 12 which is 0000 1100 |
| | Binary OR | (A | B) | It returns 12 which is 0000 1100 |
^ | Binary XOR | (A ^ B) | It returns 49 which is 0011 0001 |
~ | One’s Complement | (~A ) | It returns -60 which is 1100 0011 |
<< | shift left | A << 2 | It returns 240 which is 1111 0000 |
>> | shift right | A >> 2 | It returns 15 which is 0000 1111 |
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
public class Main { public static void main(String[] args) { //Variables Definition and Initialization int num1 = 40, num2 = 5, num3 =0; System.out.println("W3Adda - Java Bitwise Operators"); //Bitwise AND System.out.println("num1 & num2 = " + (num1 & num2)); //Bitwise OR System.out.println("num1 | num2 = " + (num1 | num2) ); //Bitwise XOR System.out.println("num1 ^ num2 = " + (num1 ^ num2) ); //Binary Complement Operator System.out.println("~num1 = " + ~num1 ); //Binary Left Shift Operator num3 = num1 << 2; System.out.println("num1 << 1 = " + num3 ); //Binary Right Shift Operator num3 = num1 >> 2; System.out.println("num1 >> 1 = " + num3 ); //Shift right zero fill operator num3 = num1 >>> 2; System.out.println("num1 >>> 1 = " + num3 ); } } |
When you run the above java program, you will see the following output.
Output:-