DEV Community

Cover image for Understanding Bitwise Operators In Java
Cal Afun
Cal Afun

Posted on

Understanding Bitwise Operators In Java

Before we dive deep into today's blog, I want us to talk about what bits are. Bits are the smallest piece of information a computer understands. Bits only have 2 values; 0 or 1.
0 usually meaning off or false
1 usually meaning on or true

Computers represent everything from symbols to text and numbers with 0's and 1's, and a combination of these 0's and 1's forms a binary number.
For example; the decimal number 5 is just a 101 in binary and this is 3 bits.

Bitwise Operators

Bitwise operators allow you to work directly with the individual bits inside the integer. Java provides; AND(&), OR(|), XOR(6^), NOT(~).
These operators allow us to work directly with the binary representation of numbers.

Bitwise Shift Operators

When working with bits in programming, two operators you’ll often encounter are << (left shift) and >> (right shift). At first, they may look a little intimidating, but once you get the intuition, they’re actually very powerful and surprisingly easy to understand.

  1. The Left Shift Operator << Think of the << operator as pushing all the bits in a number to the left, and filling the empty spaces on the right with zeros. Example: int x = 5 << 1; 5 in binary = 0101 Shift left by 1 → 1010 Result = 10

Intuition:
Each left shift is the same as multiplying by 2:
5 << 1 = 5 × 2 = 10
5 << 2 = 5 × 4 = 20
So, << is basically a fast way to multiply numbers by powers of 2.

  1. The Right Shift Operator >> The >> operator works the opposite way: it pushes all the bits in a number to the right, filling the empty spaces on the left with either zeros or the sign bit (depending on the language and whether the number is positive or negative).

Example:
int y = 20 >> 1;
20 in binary = 10100
Shift right by 1 → 01010
Result = 10
Intuition:
Each right shift is the same as dividing by 2 (ignoring remainders):
20 >> 1 = 20 ÷ 2 = 10
20 >> 2 = 20 ÷ 4 = 5
So, >> is like a quick way to divide numbers by powers of 2.

Why Are Shifts Useful?
Bit masking – Used to check or manipulate specific bits in a number.
Efficiency – Shifts can multiply or divide by 2 much faster than arithmetic operations.
Low-level programming – Essential in hardware control, graphics, compression, and cryptography.

Quick Intuition Recap
x << n → Shift left → Multiply by 2^n
x >> n → Shift right → Divide by 2^n

Once you see shift operators as shortcuts for multiplying and dividing by powers of two, they stop being scary and start becoming powerful tools. Whether you’re doing system programming, optimizing code, or just learning about bits, << and >> will show up everywhere.

Top comments (0)