Bitwise Operators in Java
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.
AND (&)
Each result bit is 1 only where both inputs have a 1 in that position.
OR (|)
Each result bit is 1 where either input has a 1 in that position.
XOR (^)
Each result bit is 1 where exactly one input has a 1, and 0 where the two inputs agree.
NOT (~)
Flips every bit of a single value, turning every 0 into a 1 and vice versa.
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.
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 |.
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)); }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.