How does the Bitwise and Operator Work in Java?
The bitwise AND operator (&) in Java compares the bits of two operands and returns a result where each bit is set to 1 if both corresponding bits are 1; otherwise, the bit is set to 0. For example:
int result = 5 & 3; // result is 1 because binary 5 is 101, and binary 3 is 011.
In Java, the bitwise AND operator (&) performs a binary operation on two integers, bit by bit.
Here’s a breakdown of how the bitwise AND operator works:
– 1 & 1 = 1 (both bits are 1, so the result is 1)
– 1 & 0 = 0 (one bit is 0, so the result is 0)
– 0 & 1 = 0 (one bit is 0, so the result is 0)
– 0 & 0 = 0 (both bits are 0, so the result is 0)
For example:
– 5 & 3:
– 5 in binary is 101
– 3 in binary is 011
– 101 & 011 = 001, which is 1 in decimal
So, 5 & 3 equals 1.
The bitwise AND operator is often used for:
– Bit masking: to extract specific bits from an integer
– Flag checking: to check if a specific flag is set in an integer
– Data compression: to pack multiple values into a single integer
Here’s an example of using bitwise and for flag checking:
public class Flag Checker {public static final int ADMIN_FLAG = 1; // 0001
public static final int MODERATOR_FLAG = 2; // 0010
public static void String [] args) {
int user Flags = ADMIN_FLAG | MODERATOR_FLAG; // 0011
if ((user lags & ADMIN_FLAG) != 0) {System.out.println(“User is an admin”)
if ((user Flags & MODERATOR_FLAG)!= 0)
System.out.println(“User is a moderator”)