Learn Java
import com.learnjava.operators.OpBitwise;

Bitwise Operators in Java

@Concept

Bitwise operators work on the individual binary bits making up an integer, rather than on its value as a whole number. & (AND) and | (OR) compare corresponding bits between two numbers; ^ (XOR) sets a bit when exactly one of the two inputs has it set; ~ (NOT) flips every bit; and the shift operators, << and >>, slide all the bits left or right by a given number of positions.

Bitwise operators show up far less often than arithmetic ones in everyday application code, but they're the standard tool for flag sets — packing several true/false options into one int — low-level protocol or file-format parsing, and fast multiplication or division by powers of two via shifting.

@HowItWorks
1

AND (&)

Each result bit is 1 only where both inputs have a 1 in that position.

2

OR (|)

Each result bit is 1 where either input has a 1 in that position.

3

XOR (^)

Each result bit is 1 where exactly one input has a 1, and 0 where the two inputs agree.

4

NOT (~)

Flips every bit of a single value, turning every 0 into a 1 and vice versa.

5

Left shift (<<) and right shift (>>)

Slide all bits left or right by a given count, equivalent to multiplying or dividing by a power of two.

6

A practical use: flag sets

Combining several boolean options into one int, where each bit represents one on/off flag, checked and set with & and |.

@Example
public class BitwiseDemo {
public static void main(String[] args) {
int a = 6;
int b = 3;
System.out.println("a & b: " + (a & b));
System.out.println("a | b: " + (a | b));
System.out.println("a << 1: " + (a << 1));
}
}
Output
a & b: 2
a | b: 7
a << 1: 12
16 is 110 in binary and 3 is 011, so a & b compares each position — only the middle bit matches on both, giving 010, which is 2.
2a | b combines every bit set in either number, giving 111, which is 7.
3a << 1 shifts 110 one place left to 1100, which is 12 — the same as multiplying 6 by 2.
4All three println calls run once each, showing AND, OR, and shift side by side.
@UseCases
Packing several boolean settings into a single int as a flag set
Parsing binary file formats or network protocols that pack multiple fields into one integer
Multiplying or dividing by a power of two quickly using a shift instead of * or /
Toggling a specific bit on or off without disturbing the others

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Java yourself — building beats watching.