0

Why the results of this two lines are different in java?

int a = 1;
System.out.println(a << 32); //output: 1
System.out.println(a << 31 << 1); //output: 0
Hum6
  • 241
  • 1
  • 2
  • 3

1 Answers1

2

Per JLS 8 ยง 15.19

If the promoted type of the left-hand operand is int, then only the five lowest-order bits of the right-hand operand are used

When shifting an int the shift distance is thus effectively the value of the right operand mod 32 (at least when the right operand is non-negative). So a << 32 is basically the same as a << 0, i.e., just a. But a << 31 << 1 first shifts a, whose value is 0x00000001, left by 31 to yield 0x80000000, which is then shifted left by 1 to yield 0x00000000.

Kevin Anderson
  • 4,568
  • 3
  • 13
  • 21