liveBook · Manning

Unsigned right shift

As explained in 100 Java Mistakes and How to Avoid Them

An unsigned right shift moves integer bits toward less significant positions while filling the most significant positions with zeros.

Unsigned right shift (`>>>`) moves an integer’s bit representation rightward and fills the left side with zeros. For a positive `int`, shifting right one bit is equivalent to dividing by two. For a negative value, it instead treats the bit pattern as a positive value larger than `MAX_VALUE`. section 4.2.1

int a = 1_000_000_000;
int b = 2_000_000_000;
int average = (a + b) >>> 1;     #1

Use `(a + b) >>> 1` to compute the midpoint of two nonnegative `int` values when their sum may overflow. The shift recovers the intended midpoint from the wrapped bit pattern. section 4.2.1

Use this overflow workaround carefully:

  • Restrict it to inputs that cannot be negative; the trick does not produce a correct average for negative inputs. section 4.2.1
  • Prefer computing the intermediate sum as `long` when possible; this is simple, only slightly slower, and also supports averages of more than two `int` values. section 4.2.1
  • Watch large-input algorithms such as binary search, where overflow can stay hidden until an array exceeds 2^30 elements. section 4.2.1

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains bit-level shift behavior, contrasts positive and negative operands, and gives a midpoint use case and limitation.
Examples
Uses an overflowed average of `1_000_000_000` and `2_000_000_000` and a large-array binary-search failure.
What it assumes
Teaches the relevant Java `int` bit-shift behavior while relying on familiarity with integer arithmetic.
What you can do after
Apply it to calculate a nonnegative `int` midpoint without being misled by intermediate-sum overflow.
How it connects
Connects unsigned right shift with integer overflow, binary search, `long`, and `BigInteger`.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.