My need to research remainder operator started when I encountered a puzzle in Java Puzzlers book where is the usual function for deciding whether the number is odd or not:

1 2 3 | public static boolean isOdd(int number) { return number % 2 == 1; } |

Quite standard standard function because odd number is defined as leaving a remainder of 1 after division by 2. But this works only for positive numbers because

1 2 3 4 | 3 % 2 // result is +1 -3 % 2 // result is -1 3 % -2 // result is +1 -3 % -2 // result is -1 |

In the next example I’ll show why, despite being odd number, the result is **False**, i.e. not being odd:

1 2 3 4 5 6 | // Step 1 -3 % 2 // result is -1 // Step 2 -1 == 1 // result is false // Step 3 // function returns value false |

The best remedy for this situation is to test whether the number is even because

1 2 3 4 | 2 % 2 // result is 0 -2 % 2 // result is 0 2 % -2 // result is 0 -2 % -2 // result is 0 |

## Floating point and remainder

Although I am not sure at the moment when to use remainder on float and double, it is possible to use modulo operation on numbers with floating point. Just be careful because in Java by default modulo operation is defined for integers and float the same way, (a/b)*b+(a%b). If you need to use modulo operation according to IEEE 754, there’s a function in Math library IEEEremainder(double dividend, double divisor) .