Bitwise & vs Logical && Operators in Java
In Java, understanding the difference between bitwise &
and logical &&
operators is crucial for writing efficient and correct code. These operators, while sometimes appearing similar, serve different purposes and are used in different contexts. This article provides a comprehensive explanation of both operators, along with ample code examples to illustrate their usage.
Bitwise &
Operator
Definition
The bitwise &
(AND) operator performs a binary AND operation between corresponding bits of two integers. Each bit in the result is set to 1
if and only if the corresponding bits in both operands are 1
.
Syntax
int result = a & b;
Example
public class BitwiseANDExample {
public static void main(String[] args) {
int a = 5; // binary: 0101
int b = 3; // binary: 0011
int result = a & b; // result: 0001 (decimal: 1)
System.out.println("Bitwise AND of " + a + " and " + b + " is " + result);
}
}
Explanation
In the example above:
5
in binary is0101
3
in binary is0011
- Performing
0101 & 0011
results in0001
(binary), which is1
in decimal.