CKTIS / Java
Bitwise AND operator (&)
The & operator preserves bits that are 1 in both integral operands. Use it to mask values and test flags. With boolean values, it means AND without short-circuit evaluation.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
left & rightThe & operator sets a result bit to 1 only when both corresponding operand bits are 1. A mask selects bits: 0b1101 & 0b0100 produces 0b0100, or 4.
Integral operands undergo binary numeric promotion. If either operand is long, the other operand is widened directly to long if needed, and the result is long. Otherwise, any byte, short, or char operand is widened to int, and the result is int. float and double are not allowed. Wrapper objects require unboxing; unboxing null throws NullPointerException.
Use parentheses when testing flags: (flags & mask) != 0 tests whether any mask bit is set, while (flags & mask) == mask tests whether all are set. Operators == and != have higher precedence than &.
With boolean or Boolean, & means logical AND. Unlike &&, it does not skip the right operand when the left is false. Do not use it as a short-circuit guard against dereferencing null.
Examples
public class Main {
public static void main(String[] args) {
int flags = 0b1101;
int mask = 0b0100;
System.out.println(flags & mask);
System.out.println((flags & mask) != 0);
}
}Result
4 true
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.