1

At specified in JLS8 at §JLS-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 as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & (§15.22.1) with the mask value 0x1f (0b11111). The shift distance actually used is therefore always in the range 0 to 31, inclusive.

I am not clear about this statement in bold . An example is much appreciated.

Cœur
  • 37,241
  • 25
  • 195
  • 267
optional
  • 3,260
  • 5
  • 26
  • 47

1 Answers1

8

It's Java exploiting compiler optimisations from the C and C++ worlds. For a 32 bit int, using an bit-shift argument greater than or equal to 31 will set the resulting value to 0 for a positive int. (For a negative argument the behaviour in C and C++ on shifting is implementation defined).

Whereas in C and C++, actually using a value greater than 31 for a 32 bit int is in fact undefined behaviour, the Java bods have actually defined the behaviour specifically and simply perform the shift with an argument modulo 32 (which is what the majority of C and C++ compilers actually do). This method is mentioned explicitly in the JLS snippet you've quoted.

Extracting the lowest five order bits of a number is equivalent to taking that number modulo 32.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • I am not clear about the statement in bold .I need an example if you can tell me with an example – optional Jul 13 '17 at 08:50
  • I've added a final sentence. Is it still not clear? – Bathsheba Jul 13 '17 at 08:51
  • Actually the last statement is what I wanted . I need to go back to masking ,I think. BTW Thanks – optional Jul 13 '17 at 08:54
  • 3
    To me this epitomises why I think that *every* programmer should have a grounding in C. For me, C was the first living language to emerge from the primordial soup of language experimentation. – Bathsheba Jul 13 '17 at 08:56
  • I actually am , but now It really required for me to go back there for more grounding. – optional Jul 13 '17 at 08:58
  • "the Java bods have actually defined the behaviour specifically" <— What's a "bod" in this context? – M. Justin Nov 28 '21 at 06:04