Understanding Java Bitwise Operators
In Java, bitwise operators are used to perform bitwise operations on integer data types. These operators work at the binary level, manipulating individual bits of the operands.
Bitwise Operators:
&Bitwise AND: Performs bitwise AND between corresponding bits of two operands.|Bitwise OR: Performs bitwise OR between corresponding bits of two operands.^Bitwise XOR: Performs bitwise XOR (exclusive OR) between corresponding bits of two operands.~Bitwise NOT: Flips the bits of the operand, changing 0s to 1s and vice versa.<<Left Shift: Shifts the bits of the left operand to the left by a specified number of positions.>>Right Shift: Shifts the bits of the left operand to the right by a specified number of positions, filling the vacant positions with the sign bit.>>>Unsigned Right Shift: Shifts the bits of the left operand to the right by a specified number of positions, filling the vacant positions with zeros.
Examples:
Here are examples of using bitwise operators in Java:
int a = 5; // Binary: 0101
int b = 3; // Binary: 0011
// Bitwise AND
int andResult = a & b; // Result: 1 (Binary: 0001)
// Bitwise OR
int orResult = a | b; // Result: 7 (Binary: 0111)
// Bitwise XOR
int xorResult = a ^ b; // Result: 6 (Binary: 0110)
// Bitwise NOT
int notResultA = ~a; // Result: -6 (Binary: 11111010)
// Left Shift
int leftShiftResult = a << 1; // Result: 10 (Binary: 1010)
// Right Shift
int rightShiftResult = a >> 1; // Result: 2 (Binary: 0010)
// Unsigned Right Shift
int unsignedRightShiftResult = a >>> 1; // Result: 2 (Binary: 0010)
Note:
Bitwise operators are useful for low-level manipulation of binary data. They are often used in scenarios where individual bits of integers need to be controlled or manipulated.