Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Operators

Java bitwise operators

Reference for Java bitwise operators &, |, ^ and ~: how they work on int and long, masks and flags, two's complement, and Integer helper methods.

Bitwise operators work on the individual bits of integer values. & keeps the bits that are set in both operands, | keeps bits set in either, ^ keeps bits that differ, and the unary ~ flips every bit. They apply to byte, short, char, int and long; smaller types are first promoted to int.

They are used for flags and masks, low-level protocols, hashing and compact data structures. Integers use two's complement, so ~x equals -x - 1.

Java
int mask = 0b1010;
int bits = 0b0110 & mask;   // 0b0010

Try it

Java AND, OR, XOR and NOT

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Flags and tricks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
a & b     // AND
a | b     // OR
a ^ b     // XOR
~a        // complement (unary)
Operator Bit result Typical use
& 1 only if both bits are 1 test or clear bits with a mask
| 1 if either bit is 1 set bits
^ 1 if the bits differ toggle bits
~ flips every bit build "all except" masks

Usage notes

  • Promotion. byte and short operands become int, so ~b of a negative byte gives an int. Mask with & 0xFF to get an unsigned byte value.
  • Mixed widths. If one operand is long, the other is widened to long. A negative int widens by sign extension, which fills the upper 32 bits with ones; mask with 0xFFFFFFFFL to avoid that.
  • On booleans the same symbols are logical operators that do not short-circuit; see Logical operators. & on an int and a boolean does not compile.
  • Precedence is low. x & 1 == 1 parses as x & (1 == 1) and fails to compile. Always write (x & 1) == 1.
  • Helpers. Integer.bitCount, Integer.highestOneBit, Integer.numberOfTrailingZeros, Integer.reverse and Long.* equivalents are clearer than hand-rolled loops. For many flags, EnumSet or BitSet read better.
  • Literals. Use 0b for binary, 0x for hex and underscores for readability (0b1100_1010).
  • Shifts have their own operators; see Shift operators.