Java Shift Operators Explained: <<, >> and >>> with Examples

0

Shift operators allow you to move the individual bits of an integer to the left or right. They are especially useful when working with binary data, bit masks, compact flags, low-level algorithms, and performance-sensitive code.

Java provides three shift operators: << for left shift, >> for signed right shift, and >>> for unsigned right shift. The two right-shift operators look similar, but they behave very differently when the number is negative.

Shift Operators at a Glance

Operator Name Direction Important Behavior
<< Left Shift Left Zeros enter from the right
>> Signed Right Shift Right Preserves the sign bit
>>> Unsigned Right Shift Right Zeros enter from the left

Why Shift Operators Exist

Computers store integer values using bits. Sometimes moving those bits is exactly the operation a program needs. For example, shifting a binary value one position to the left is closely related to multiplying by two, while shifting it right is related to dividing by two for many positive integer values.

But shift operators are not simply shortcuts for arithmetic. Their real purpose is to manipulate the binary representation of integral values.

Important: Shift operators work with integral values. The right-hand operand specifies how many bit positions to shift.

Left Shift Operator (<<)

The left shift operator moves every bit to the left by the specified number of positions. Zero bits are inserted on the right.

int number = 5;

int result = number << 1;

System.out.println(result);

The binary representation can be viewed as:

5       = 0101
5 << 1  = 1010

The result is 10.

For many positive values, shifting left by one position is equivalent to multiplying by two.

int x = 7;

System.out.println(x << 1);
System.out.println(x << 2);

The first expression produces 14, while the second produces 28.

Left Shift and Multiplication

A left shift by n positions is mathematically related to multiplying by 2ⁿ, provided the result remains within the appropriate range.

int number = 3;

int result = number << 3;

System.out.println(result);

Three positions means multiplication by , so the result is 24.

Remember: Bit shifting can resemble multiplication or division, but think of it primarily as bit manipulation. Overflow can produce results that do not match ordinary mathematical expectations.

Signed Right Shift (>>)

The signed right shift operator moves bits toward the right. Unlike the left shift, the empty positions on the left are filled with copies of the original sign bit.

For a positive number, the sign bit is zero, so zeros enter from the left.

int number = 20;

int result = number >> 2;

System.out.println(result);

The result is 5. For positive values, a right shift by two positions is equivalent to integer division by 4.

20 / 4 = 5

Why Is It Called Signed Right Shift?

Java integers are signed. The highest bit participates in representing the sign of the value. The >> operator preserves that sign by copying the original sign bit into the newly opened positions.

This behavior becomes important when shifting negative numbers.

int number = -8;

int result = number >> 1;

System.out.println(result);

The result is -4. The sign remains negative because the leftmost positions are filled with ones.

Unsigned Right Shift (>>>)

The unsigned right shift operator also moves bits to the right, but it always fills the newly created positions on the left with zeros.

int number = 20;

int result = number >>> 2;

System.out.println(result);

For positive values, >> and >>> produce the same result because the sign bit is already zero.

The difference becomes visible with negative values.

int number = -8;

System.out.println(number >> 1);
System.out.println(number >>> 1);

The signed shift keeps the sign, producing -4. The unsigned shift inserts zeros instead, producing a large positive integer.

Key difference: >> preserves the sign by copying the sign bit, while >>> always inserts zeros from the left.

Comparing the Three Shift Operators

Operator Movement New Bits Negative Value Behavior
<< Left Zeros on right Can change sign and overflow
>> Right Copies sign bit Preserves negative sign
>>> Right Zeros on left Treats shifted bits without sign extension

Shift Distance

The right-hand side of a shift expression specifies the number of positions to move.

int number = 16;

int result = number >> 2;

System.out.println(result);

The value is shifted two positions to the right.

Java applies special rules to the shift distance. For an int, only the low five bits of the right-hand operand are considered, effectively limiting the shift distance to the range from 0 through 31. For a long, the effective range is 0 through 63.

Using Shift Operators with Assignment

Shift operators can also be combined with assignment.

int value = 4;

value <<= 2;

System.out.println(value);

The compound assignment shifts the value left by two positions and stores the result back into value. The final value is 16.

The same pattern works with the right-shift operators.

int value = 32;

value >>= 3;

System.out.println(value);

The result is 4.

Shift Operators and Bit Masks

Shift operators are often combined with bitwise operators to create masks dynamically.

int position = 3;

int mask = 1 << position;

System.out.println(mask);

The value 1 starts with only the lowest bit enabled. Shifting it left by three positions produces a value with the fourth bit enabled.

1 << 0 = 1
1 << 1 = 2
1 << 2 = 4
1 << 3 = 8

This pattern is extremely useful when building flags or checking specific bit positions.

Example: Setting a Specific Flag

Suppose each bit represents a feature. You can generate a mask for a particular feature using a left shift.

int featurePosition = 4;

int featureMask = 1 << featurePosition;

int settings = 0;

settings = settings | featureMask;

System.out.println(settings);

The shift creates the mask, and the bitwise OR enables that flag.

Overflow with Left Shift

A left shift does not automatically protect you from integer overflow. If significant bits are shifted beyond the available width, those bits are discarded.

int value = 1;

int result = value << 31;

System.out.println(result);

The highest bit of an int becomes set, which represents a negative value in Java's signed integer representation.

This is a good reminder that bit operations work within a fixed number of bits. They do not provide unlimited mathematical precision.

Common Beginner Mistakes

  • Confusing >> with >>>.
  • Assuming right shifting a negative number always produces the same result as normal division.
  • Forgetting that left shifts can cause overflow.
  • Ignoring Java's rules for large shift distances.
  • Thinking shift operators work directly on floating-point values.
  • Using bit shifts when ordinary arithmetic would make the code clearer.

Best Practices

  • Use shifts when the problem genuinely involves binary representation or bit manipulation.
  • Use meaningful names for shift positions and masks.
  • Use parentheses when combining shifts with other arithmetic or bitwise operations.
  • Be especially careful with negative values and signed integer overflow.
  • Choose >> or >>> based on whether sign extension is required.
  • Prefer readable arithmetic when a shift would make the intention less obvious.

Interview Insights

A common interview question asks for the difference between >> and >>>. The essential answer is that signed right shift preserves the sign by extending the sign bit, while unsigned right shift fills the new positions with zeros.

Another common question is why 1 << n is useful. It creates a value with a single bit set at position n, making it a convenient way to create bit masks.

Interviewers may also test whether you understand that shifting an int is limited by Java's rules for the shift distance and that left shifts can overflow the signed integer range.

Quick Revision

Expression Meaning Example Key Point
x << n Shift left 4 << 1 → 8 Zeros enter from the right
x >> n Signed shift right 16 >> 2 → 4 Preserves the sign
x >>> n Unsigned shift right 16 >>> 2 → 4 Zeros enter from the left
1 << n Create a bit mask 1 << 3 → 8 Sets one bit at position n

Final Takeaway

Shift operators give Java precise control over how bits move inside integral values. << moves bits left, >> moves them right while preserving the sign, and >>> moves them right while inserting zeros. They are powerful tools for bit masks, flags, binary data, and low-level programming. Mastering the difference between the two right-shift operators is particularly important because it reveals how Java handles signed integer representation at the bit level.

Post a Comment

0Comments
Post a Comment (0)