Exploring Java: Remainder operator

[CN Java] As I’ve started digging deep into Java, I’ve encountered several things which I’d like to write about to make a more permanent note in my head. In this post, I’ll focus on remainder % operator.

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:

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

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

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

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) .