Home Java Program Examples Bitwise operators in Java

Bitwise operators in Java

by anupmaurya
3 minutes read

In this tutorial, you’ll learn about Bitwise operators in Java. Java defines various bit-wise operators, which work’s on bits and performs the bit-by-bit operation. It can be applied to the integer types, long, int, short, char, and byte.

Assume if a = 60 and b = 10; now in binary format they will be as follows − 

a = 0011 1100
b = 0000 1010
-----------------
a&b = 0000 1000

a|b = 0011 1110

a^b = 0011 0110

~a = 1100 0011

The following table lists the bitwise operators −

Assume integer variable A holds 60 and variable B holds 10 then −

OperatorDescriptionExample
& (bitwise and)It returns bit by bit AND of input values, i.e, if both bits are 1, it gives 1, else it gives 0. (A & B) will give 8 which is 0000 1000
| (bitwise or)It returns bit by bit OR of input values, i.e, if either of the bits is 1, it gives 1, else it gives 0. (A | B) will give 62 which is 0011 1110
^ (bitwise XOR)It returns bit by bit XOR of input values, i.e, if corresponding bits are different, it gives 1, else it gives 0. (A ^ B) will give 54 which is 0011 0110
~ (bitwise compliment)It returns the one’s complement representation of the input value, i.e, with all bits inverted, which means it makes every 0 to 1, and every 1 to 0(~A ) will give -61 which is 1100 0011 in 2’s complement form due to a signed binary number.
<< (left shift)Shifts the bits of the number to the left and fills 0 on voids left as a result. Similar effect as of multiplying the number with some power of two. A << 2 will give 240 which is 1111 0000
>> (right shift)Shifts the bits of the number to the right and fills the voids left with the sign bit (1 in case of negative number and 0 in case of positive number). The leftmost bit and a depends on the sign of initial number. Similar effect as of dividing the number with some power of two. A >> 2 will give 15 which is 1111
>>> (zero fill right shift)Shift right zero fill operator. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros.A >>>2 will give 15 which is 0000 1111
Bitwise operators in Java

You may also like

Adblock Detected

Please support us by disabling your AdBlocker extension from your browsers for our website.