`java (0 % 2 != 0) == false`

Michael picture Michael · May 9, 2012 · Viewed 41.5k times · Source

The part I keep getting stuck on is boolean(0 % 2 !=0) == false. I mean if 2 goes into 0, 0 times then the remainder would be 2, and 2 does not equal 0. So it should be true. Yet but when I put the boolean in my java program it is treating it as false. Anyone know why?

The only logical answer I can wrap my head around is that maybe integers go into 0 and infinite number of times and so are recognized as false, anyone?

Answer

NPE picture NPE · May 9, 2012

There are two steps:

  • 0 % 2 evaluates to 0.

  • 0 != 0 evaluates to false.

To elaborate on the first step, the JLS defines the % operator like so:

The binary % operator is said to yield the remainder of its operands from an implied division; the left-hand operand is the dividend and the right-hand operand is the divisor.

The remainder of dividing 0 by 2 is 0 and not 2 as you seem to think.