Skip to content
C

Bitwise Operators

Bitwise operators work directly on the individual bits (0s and 1s) that make up a number, rather than on the number as a whole. Java provides operators like & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), and >> (right shift).


1. What are Bitwise Operators?

Bitwise operators work directly on the individual bits (0s and 1s) that make up a number, rather than on the number as a whole. Java provides operators like & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), and >> (right shift).

2. Why is it used?

Bitwise operators are used in performance-critical tasks, such as low-level programming, working with flags, encryption logic, and optimizing certain calculations by manipulating bits directly instead of using normal arithmetic.

3. Real-Life Example

Think of a row of light switches, where each switch is either ON (1) or OFF (0). Bitwise operators let you check, combine, or flip specific switches individually, rather than dealing with the whole row of switches as one single unit.

4. Syntax

java
a & b // bitwise AND a | b // bitwise OR a ^ b // bitwise XOR ~a // bitwise NOT (complement) a << 1 // left shift by 1 bit a >> 1 // right shift by 1 bit

5. Example Program

java
public class BitwiseDemo { public static void main(String[] args) { int a = 5; // binary: 0101 int b = 3; // binary: 0011 System.out.println("AND: " + (a & b)); System.out.println("OR: " + (a | b)); System.out.println("XOR: " + (a ^ b)); System.out.println("Left Shift: " + (a << 1)); } }

Output:

AND: 1
OR: 7
XOR: 6
Left Shift: 10

6. Key Points to Remember

  • Bitwise operators work on the binary form of numbers, not the decimal value directly.
  • << (left shift) roughly doubles a number for each shift; >> (right shift) roughly halves it.
  • These are used less often in everyday business applications but are important for interviews and system-level programming.

Mock Test

  • Bitwise Operators - Quick Test

    10 questions on &, |, ^, ~, << and >> working on the bits of a number.

    10 questions · 10 min · Easy
    Start Mock Test

Coding Problems