Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The >>= (signed right shift assignment) operator is a compound assignment operator that shifts the binary representation of the left operand to the right by a specified number of bits, performs sign extension, and assigns the resulting value back to the left operand.

Syntax

leftOperand >>= rightOperand;
This operation is logically equivalent to:
leftOperand = (Type) (leftOperand >> rightOperand);

Bitwise Mechanics

1. Sign Extension Unlike the unsigned right shift (>>>=), the >>= operator preserves the sign of the original value by inspecting the Most Significant Bit (MSB).
  • If the left operand is positive (MSB is 0), the vacated leftmost bits are padded with 0s.
  • If the left operand is negative (MSB is 1), the vacated leftmost bits are padded with 1s.
2. Bit Discarding Bits shifted to the right beyond the Least Significant Bit (LSB) are permanently discarded. 3. Shift Distance Masking Java limits the shift distance based on the data type of the left operand to prevent out-of-bounds shifts:
  • int operands: The right operand is implicitly masked with 0x1F (bitwise AND with 31). For example, x >>= 33 is executed as x >>= 1.
  • long operands: The right operand is implicitly masked with 0x3F (bitwise AND with 63). For example, y >>= 65 is executed as y >>= 1.
4. Implicit Narrowing Conversion When used with types smaller than int (byte, short, char), the left operand is first promoted to an int for the shift operation. The compound assignment operator then automatically applies an implicit cast to narrow the result back to the original type. This prevents the compilation errors that would normally occur when assigning an int result back to a smaller integral type.

Execution Examples

Positive Integer Shift
int a = 20;       // Binary: 00000000 00000000 00000000 00010100
a >>= 2;          // Shifts right by 2, pads with 0s
// Result: 5      // Binary: 00000000 00000000 00000000 00000101
Negative Integer Shift
int b = -20;      // Binary: 11111111 11111111 11111111 11101100
b >>= 2;          // Shifts right by 2, pads with 1s (sign extension)
// Result: -5     // Binary: 11111111 11111111 11111111 11111011
Implicit Casting with Byte
byte c = -128;    // Binary: 10000000 (promoted to int: 1111...10000000)
c >>= 1;          // Shifts right by 1, pads with 1s, implicitly casts back to byte
// Result: -64    // Binary: 11000000
Master Java with Deep Grasping Methodology!Learn More