Learn how to perform operations on the individual bits of integer-type numbers, a fundamental concept for low-level programming and optimization.
Java · intermediate · 25 min · 14 steps · free
public class BitwiseDemo {
public static void main(String[] args) {
// Initial values
int a = 5; // Binary: 0101
int b = 3; // Binary: 0011
// Bitwise AND (&)
int resultAnd = a & b; // 0101 & 0011 = 0001 (1)
System.out.println("a & b = " + resultAnd);
// Bitwise OR (|)
int resultOr = a | b; // 0101 | 0011 = 0111 (7)
System.out.println("a | b = " + resultOr);
// Bitwise XOR (^)
int resultXor = a ^ b; // 0101 ^ 0011 = 0110 (6)
System.out.println("a ^ b = " + resultXor);
// Bitwise Complement (~)
int resultNot = ~a; // ~0101 -> ...11111010 (-6)
System.out.println("~a = " + resultNot);
// Left Shift (<<)
int resultLeftShift = a << 1; // 0101 << 1 = 1010 (10)
System.out.println("a << 1 = " + resultLeftShift);
// Signed Right Shift (>>)
int resultRightShift = a >> 1; // 0101 >> 1 = 0010 (2)
System.out.println("a >> 1 = " + resultRightShift);
}
}a and initialize it with the value 5. In a 4-bit representation, 5 is 0101.b and initialize it with 3. In a 4-bit representation, 3 is 0011.&). This operation compares each bit of a and b. If both bits are 1, the result is 1; otherwise, it is 0. (0101 & 0011 = 0001)|). If either bit is 1, the result is 1; otherwise, it is 0. (0101 | 0011 = 0111)^). If the bits are different, the result is 1; otherwise, it is 0. (0101 ^ 0011 = 0110)~). This inverts all bits. ~00...0101 becomes 11...1010, which is the two's complement representation of -6.<<). This shifts all bits of a to the left by 1 position, adding a 0 at the end. (0101 << 1 = 1010). This is equivalent to multiplying by 2.>>). This shifts all bits of a to the right by 1 position. The leftmost bit (sign bit) is copied. (0101 >> 1 = 0010). This is equivalent to dividing by 2.&, |) with their logical counterparts (&&, ||). Logical operators work on boolean expressions, while bitwise operators work on the bits of integral types.~) works with two's complement representation for negative numbers.() to clarify the order of operations when mixing bitwise and other operators to improve code readability.>> (preserves sign) and unsigned right shift >>> (fills with zeros). Use >>> when you need to treat a number as an unsigned value.← Increment/Decrement Operators · Ternary Operator →