If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In Java, bitwise operators perform operations on individual bits of integral data types (byte, short, int, long, and char). These operators are useful for low-level manipulation of data, dealing with flags, and optimizing certain algorithms. There are six bitwise operators in Java:
&
):Example:
javaCopy code
int a = 10; // Binary: 1010
int b = 6; // Binary: 0110
int result = a & b; // 1010 & 0110 = 0010 (Decimal 2)
|
):Example:
javaCopy code
int a = 10; // Binary: 1010
int b = 6; // Binary: 0110
int result = a | b; // 1010 | 0110 = 1110 (Decimal 14)
^
):Example:
javaCopy code
int a = 10; // Binary: 1010
int b = 6; // Binary: 0110
int result = a ^ b; // 1010 ^ 0110 = 1100 (Decimal 12)
~
):Example:
javaCopy code
int a = 10; // Binary: 1010
int result = ~a; // ~1010 = 0101 (Decimal 5) - The sign bit is also flipped
<<
):Example:
javaCopy code
int a = 5; // Binary: 0101
int result = a << 2; // 0101 << 2 = 010100 (Decimal 20)
>>
):Example:
javaCopy code
int a = -10; // Binary: 11111111111111111111111111110110 (32-bit representation of -10)
int result = a >> 2; // 11111111111111111111111111110110 >> 2 = 11111111111111111111111111111101 (Decimal -3)
These bitwise operators can be handy in various scenarios, such as setting and clearing specific bits, working with flags in binary representation, or optimizing certain computations in specific algorithms. They provide a way to manipulate data at the bit level, which can be particularly useful in certain programming applications.
Comments: 0