In Java, bitwise operators are used to perform operations on individual bits of integer types (int
, long
, short
, char
, and byte
).
We can apply this operator for integral type also in boolean as well.
There are several bitwise operators, each of which operates on corresponding bits of two integer values.
Here are the bitwise operators in Java:
Bitwise AND (
&
):- Performs a bitwise AND operation between each pair of corresponding bits.
int a = 5; // binary: 0101
int b = 3; // binary: 0011
int result = a & b; // binary: 0001 (1 in decimal)
Bitwise OR (
|
):- Performs a bitwise OR operation between each pair of corresponding bits.
int x = 5; // binary: 0101
int y = 3; // binary: 0011
int result = x | y; // binary: 0111 (7 in decimal)
Bitwise XOR (
^
):- Performs a bitwise exclusive OR operation between each pair of corresponding bits. The result is 1 if the bits are different.
int p = 5; // binary: 0101
int q = 3; // binary: 0011
int result = p ^ q; // binary: 0110 (6 in decimal)
Bitwise NOT (
~
):Inverts the bits of a single operand.
This operator is only applicable for integral not for boolean.
System.out.println(~5); // -6
System.out.println(~-6); // 5
Left Shift (
<<
):- Shifts the bits of the left operand to the left by a specified number of positions.
int value = 5; // binary: 0000 0000 0000 0000 0000 0000 0000 0101
int result = value << 2; // binary: 0000 0000 0000 0000 0000 0000 0001 0100 (20 in decimal)
Right Shift (
>>
):- Shifts the bits of the left operand to the right by a specified number of positions. The sign bit is used to fill the vacant positions (for signed integers).
int number = -16; // binary: 1111 1111 1111 1111 1111 1111 1111 0000
int result = number >> 2; // binary: 1111 1111 1111 1111 1111 1111 1111 1100 (-4 in decimal)
Unsigned Right Shift (
>>>
):- Similar to right shift (
>>
), but the vacant positions are filled with zeros.
- Similar to right shift (
int num = -16; // binary: 1111 1111 1111 1111 1111 1111 1111 0000
int result = num >>> 2; // binary: 0011 1111 1111 1111 1111 1111 1111 1100 (1073741820 in decimal)
Boolean compliment operator (
!
)We can apply this operator only for Boolean type.
If you apply this operator on any other type then will get compiled time error.
System.out.println(!4); // ! cannot be applied to int
System.out.println(!true); // false
Bitwise Operator | Applicable for |
& , ` | , ^` |
~ | For integral type only |
! | For Boolean type only |
Bitwise operators are often used in low-level programming, graphics programming, and situations where manipulating individual bits is necessary for efficient operations.