What is Bitwise Operator in Java: Explanation and Examples
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.
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 } }
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, andbyte.