← Back to Chapters

Java Bitwise Operators

? Java Bitwise Operators

? Quick Overview

Bitwise operators in Java work directly on the binary representation of integers. They are mainly used for low-level programming, performance optimization, and manipulating individual bits.

? Key Concepts

  • Operate at the bit (0 and 1) level
  • Faster than arithmetic operations in some cases
  • Mainly used with int and long data types
  • Useful in flags, masks, and system-level programming

? Syntax & Theory

Java provides six main bitwise operators:

  • & Bitwise AND
  • | Bitwise OR
  • ^ Bitwise XOR
  • ~ Bitwise NOT
  • << Left Shift
  • >> Right Shift

? Code Example

? View Code Example
// Demonstrating Java bitwise operators
int a = 5;
int b = 3;

System.out.println(a & b);
System.out.println(a | b);
System.out.println(a ^ b);
System.out.println(~a);
System.out.println(a << 1);
System.out.println(a >> 1);

? Live Output / Explanation

a = 5 → 0101
b = 3 → 0011

  • a & b → 1 (0001)
  • a | b → 7 (0111)
  • a ^ b → 6 (0110)
  • ~a → -6 (two’s complement)
  • a << 1 → 10 (left shift)
  • a >> 1 → 2 (right shift)

? Interactive Bitwise Visualizer

Change the numbers to see the binary logic update instantly.

A (5) 00000101
B (3) 00000011
Result (1) 00000001

✅ Tips & Best Practices

  • Use bitwise operators only when needed
  • Comment your code clearly for readability
  • Avoid using them in beginner-level logic
  • Prefer clarity over micro-optimizations

? Try It Yourself

  • Check if a number is even or odd using bitwise AND
  • Swap two numbers using XOR
  • Use left shift to multiply a number by 2