2
System.out.println(4 & 0xFFFF);
System.out.println(4 & 0xFFFF - 1);
int i = 4 & 0xFFFF;
System.out.println(i - 1);

I tried these four lines. But the first and second print will all print out 4. However, the last one will print out 3. I really cannot figure out why... shouldn't the second print prints out 3?

1

1 Answer 1

3

Use () to make it clear what you expect to be the order of operation:

    System.out.println( 4 & (0xFFFF - 1) );
    System.out.println( (4 & 0xFFFF) - 1 );

Without the () the order of operation is the first case;

1
  • Ah yes. Thank you!!!
    – sbgbbt
    May 20, 2020 at 3:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.