Skip to main content
The <<= (left shift assignment) operator is a compound assignment operator that performs a bitwise left shift on its left operand by the number of bits specified by its right operand, and subsequently assigns the evaluated result back to the left operand.

Syntax

Mechanics

When lhs <<= rhs is executed, the Java Virtual Machine (JVM) performs the following operations:
  1. Single Evaluation: The lhs expression is evaluated exactly once.
  2. Binary Translation: The evaluated lhs is treated as a two’s complement binary integer.
  3. Bit Shifting: The bits of lhs are shifted to the left by the number of positions specified by rhs.
  4. Zero-Padding: The vacated bit positions on the right (least significant bits) are filled with zeros (0).
  5. Truncation: Bits shifted beyond the bounds of the data type’s memory size (most significant bits) are discarded.
  6. Assignment: The final bit sequence is assigned back to the memory location of lhs.

Single Evaluation and Implicit Type Casting

According to the Java Language Specification (JLS 15.26.2), the expression E1 <<= E2 is equivalent to E1 = (T) ((E1) << (E2)), where T is the data type of E1, except that E1 is evaluated only once. This single evaluation is a defining characteristic of all compound assignment operators in Java and is critical when the left-hand operand contains side effects:
Additionally, the implicit narrowing primitive conversion (T) allows shifting on smaller primitive types (byte, short, char) without requiring explicit casting, even though the bitwise shift operation internally promotes the operands to int:

Shift Distance Masking

Java limits the shift distance based on the data type of the left operand to prevent undefined behavior. The JVM applies a bitwise AND mask to the right operand (rhs) before shifting:
  • For int (and smaller types promoted to int): The shift distance is masked by 0x1F (31). Only the lower 5 bits of rhs are used. Therefore, a <<= 33 is mechanically identical to a <<= 1.
  • For long: The shift distance is masked by 0x3F (63). Only the lower 6 bits of rhs are used. Therefore, a <<= 65 is mechanically identical to a <<= 1.

Code Visualization

Sign Bit Behavior

Unlike the right shift operators (>> and >>>), there is only one left shift operator. The <<= operator does not preserve the sign bit. If a 1 is shifted into the Most Significant Bit (MSB) position of the data type, a previously positive number will become negative due to two’s complement representation.
Tired of Poor Java Skills? Fix That With Deep Grasping!Learn More