0
0
JavaConceptBeginner · 3 min read

What is Bitwise Operator in Java: Explanation and Examples

In Java, bitwise operators perform operations directly on the binary digits (bits) of integer values. They allow manipulation of individual bits using operators like &, |, ^, ~, <<, >>, and >>>.
⚙️

How It Works

Bitwise operators work by looking at the binary form of numbers, which are made up of 0s and 1s. Imagine each number as a row of tiny switches that can be either off (0) or on (1). Bitwise operators let you flip, combine, or shift these switches directly.

For example, the & operator compares two numbers bit by bit and turns on a switch only if both bits are on. The | operator turns on a switch if at least one bit is on. Shifting operators like << move all bits to the left or right, similar to sliding beads on an abacus.

This low-level control is very fast and useful when you want to work with flags, masks, or optimize performance in certain tasks.

💻

Example

This example shows how to use some common bitwise operators in Java and their results.

java
public class BitwiseExample {
    public static void main(String[] args) {
        int a = 5;  // binary 0101
        int b = 3;  // binary 0011

        System.out.println("a & b = " + (a & b));  // AND
        System.out.println("a | b = " + (a | b));  // OR
        System.out.println("a ^ b = " + (a ^ b));  // XOR
        System.out.println("~a = " + (~a));        // NOT
        System.out.println("a << 1 = " + (a << 1)); // left shift
        System.out.println("b >> 1 = " + (b >> 1)); // right shift
    }
}
Output
a & b = 1 a | b = 7 a ^ b = 6 ~a = -6 a << 1 = 10 b >> 1 = 1
🎯

When to Use

Bitwise operators are useful when you need to work with data at the bit level for efficiency or control. Common uses include:

  • Setting, clearing, or toggling specific bits in flags or options.
  • Performing fast arithmetic operations like multiplying or dividing by powers of two using shifts.
  • Encoding multiple boolean values compactly in a single integer.
  • Working with low-level device control, graphics, or network protocols where bits represent specific signals.

They are less common in everyday programming but very important in systems programming, embedded software, and performance-critical code.

Key Points

  • Bitwise operators work on the binary representation of integers.
  • They include AND (&), OR (|), XOR (^), NOT (~), and shifts (<<, >>, >>>).
  • Useful for manipulating individual bits for flags, masks, and performance.
  • Operate only on integer types like int, long, short, and byte.

Key Takeaways

Bitwise operators manipulate individual bits of integer values in Java.
They are useful for efficient low-level data handling and flag management.
Common operators include AND, OR, XOR, NOT, and bit shifts.
Bitwise operations work only on integer types, not on floating-point numbers.
Use bitwise operators when you need fast, direct control over bits.