Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE

Problem: Java int shifts: arithmetic >> keeps the sign, logical >>> fills with zeros, and shifting into the sign bit overflows.

Problem: Java int shifts: arithmetic >> keeps the sign, logical >>> fills with zeros, and shifting into the sign bit overflows.
int a = -16;
System.out.println((a >> 2) + " " + (a >>> 28) + " " + (1 << 31));
What does this print?
  1. A. 1073741820 15 -2147483648
  2. B. -4 15 2147483648
  3. C. -4 15 -2147483648
  4. D. -4 268435455 2147483648

Correct answer: C. -4 15 -2147483648

−16 is 0xFFFFFFF0. >> 2 copies the sign bit → −4 (division by 4 rounding down). >>> 28 shifts in zeros, leaving the top 4 bits 1111 = 15. 1 << 31 sets the sign bit of a 32-bit int → −2147483648; Java int cannot hold +2³¹. (Verified with a 32-bit JavaScript port, which uses the same shift semantics.)

More Coding Interview Problems questions

Exams that ask this topic