Can someone please explain why 4 & 0xFFFF - 1 is still 4?

Viewed 169
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 Answers

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;

Related