Bitwise Operators

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

What you'll learn

BitwiseDemo.java

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);
    }
}

Step by step

  1. We declare an integer variable a and initialize it with the value 5. In a 4-bit representation, 5 is 0101.
  2. Next, we declare an integer b and initialize it with 3. In a 4-bit representation, 3 is 0011.
  3. Performing Bitwise AND (&). 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)
  4. Printing the result of the AND operation.
  5. Performing Bitwise OR (|). If either bit is 1, the result is 1; otherwise, it is 0. (0101 | 0011 = 0111)
  6. Printing the result of the OR operation.
  7. Performing Bitwise XOR (^). If the bits are different, the result is 1; otherwise, it is 0. (0101 ^ 0011 = 0110)
  8. Printing the result of the XOR operation.
  9. Performing Bitwise Complement (~). This inverts all bits. ~00...0101 becomes 11...1010, which is the two's complement representation of -6.
  10. Printing the result of the Complement operation.
  11. Performing Left Shift (<<). 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.
  12. Printing the result of the Left Shift operation.
  13. Performing Signed Right Shift (>>). 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.
  14. Printing the result of the Signed Right Shift operation.

Common mistakes

Best practices

·

More in Operators