A Comprehensive Overview of Java Bitwise Operators
This article provides a detailed introduction to Java's seven bitwise operators, explains their binary logic, demonstrates shift operations, and showcases common practical uses such as power-of-two multiplication and parity checks with clear code examples and visual illustrations.
The author noticed frequent use of bitwise operations in JDK collection implementations and created this article to summarize Java's bitwise operators for readers who are unfamiliar with the topic.
Java defines seven bitwise operators—AND (&), OR (|), XOR (^), NOT (~), left shift (<<), signed right shift (>>), and unsigned right shift (>>>)—which operate on integral types (byte, short, int, long, char) but not on floating‑point or boolean values.
Bitwise operations work on binary representations; Java stores integers using two's complement, where positive numbers have identical sign, original, and complement forms, while negative numbers are represented by inverting bits and adding one.
Logical bitwise operators include AND, OR, XOR, and NOT. The article explains each operator's rule, provides visual examples (e.g., 5 & 6, 5 | 6, 5 ^ 6, ~5), and lists derived conclusions such as "any number AND 0 yields 0" and "any number OR 0 yields the number itself".
Shift operators are left shift (<<), signed right shift (>>), and unsigned right shift (>>>). Left shift multiplies by 2ⁿ, signed right shift divides positive numbers by 2ⁿ and preserves the sign bit, while unsigned right shift fills vacated bits with zeros regardless of sign.
Common practical uses demonstrated include:
Computing multiplication by powers of two using left shift: System.out.println("2^3=" + (1 << 3)); // 2^3=8 System.out.println("3*2^3=" + (3 << 3)); // 3*2^3=24 System.out.println("5*2^3=" + (5 << 3)); // 5*2^3=40
Determining parity of an integer using AND with 1: System.out.println((5 & 1) == 1 ? "奇数" : "偶数"); // 奇数 System.out.println((6 & 1) == 1 ? "奇数" : "偶数"); // 偶数 System.out.println((0 & 1) == 1 ? "奇数" : "偶数"); // 偶数 System.out.println((-1 & 1) == 1 ? "奇数" : "偶数"); // 奇数 System.out.println((-2 & 1) == 1 ? "奇数" : "偶数"); // 偶数
Calculating absolute values using a combination of XOR and signed right shift: System.out.println((-5 ^ (-5 >> 31)) - (-5 >> 31)); System.out.println((0 ^ (0 >> 31)) - (0 >> 31));
The article concludes that bitwise operators, while conceptually complex, are highly efficient and do not modify the original operand values, making them valuable tools for performance‑critical Java code.
Architect's Guide
Dedicated to sharing programmer-architect skills—Java backend, system, microservice, and distributed architectures—to help you become a senior architect.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.