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 << (left shift) operator is a binary bitwise operator in Java that shifts the two’s complement bit pattern of the left operand to the left by the number of positions specified by the right operand.
result = leftOperand << rightOperand;

Mechanics

When the << operator is applied:
  1. The bits of the leftOperand are shifted to the left by the distance of the rightOperand.
  2. The vacated bit positions on the right are filled with zeros (0).
  3. The bits shifted off the left boundary (the most significant bits, including the sign bit) are discarded.
Mathematically, shifting an integer left by nn positions is equivalent to multiplying that integer by 2n2^n, provided that the operation does not result in an overflow that alters the sign bit.

Type Promotion

Before the shift operation occurs, Java applies unary numeric promotion to the left operand:
  • If the left operand is of type byte, short, or char, it is implicitly promoted to a 32-bit int. The result of the shift will also be an int.
  • If the left operand is a long, no promotion occurs, and the result is a long.

Shift Distance Masking

To prevent undefined behavior from shifting by a distance greater than the bit-width of the operand, Java applies a bitwise AND mask to the right operand:
  • For int operands: The right operand is masked with 0x1F (31). The actual shift distance is rightOperand & 31. For example, shifting an int by 32 positions is equivalent to shifting it by 0 positions.
  • For long operands: The right operand is masked with 0x3F (63). The actual shift distance is rightOperand & 63.

Syntax Visualization

Example 1: Standard Left Shift Shifting the integer 5 left by 2 positions.
int a = 5;      // Binary: 00000000 00000000 00000000 00000101
int b = a << 2; // Binary: 00000000 00000000 00000000 00010100 (Decimal: 20)
Example 2: Negative Number Shift Shifting a negative integer (represented in two’s complement). The rightmost bits are still filled with zeros, which can eventually push the zero bits into the sign bit position, changing the sign if shifted far enough.
int a = -5;     // Binary: 11111111 11111111 11111111 11111011
int b = a << 1; // Binary: 11111111 11111111 11111111 11110110 (Decimal: -10)
Example 3: Shift Distance Masking Demonstrating how Java masks the right operand for a 32-bit int.
int a = 10;
int b = a << 33; // 33 & 0x1F evaluates to 1. Equivalent to: a << 1
// b equals 20
Master Java with Deep Grasping Methodology!Learn More