What if we needed the remainder? How would we get it? The modulus operator (which we'll often call the mod operator) gets the remainder of a division.
For example, 8 % 3 evaluates to 2 because 8 divided by 3 has a remainder of 2.
When both operands have type int, the modulus operator (with both operands) evaluates to int.
Normally, most programmers use the mod operator when both operands are positive. After all, what does remainder mean when one or both operands are negative?
Even so, Java allows for one or both operands to be negative. What is the result? First, do the mod operation as if both numbers are positive, e.g., if you are evaluating x % y, then you should evaluate |x| % |y| (where |x| is the absolute value of x. Then, if the left operand is negative, make the result negative.
Thus, -8 % 3 is -2 (left operand is negative) while 8 % -3 is 2 (left operand is positive). Using this rule, the evaluated result is negative if both operands are negative.
By the way, there is no absolute value operator in Java. I just needed to pretend it existed to explain the mod operator.
As I mentioned earlier, most programmers never use negative operands with the mod operator. They understand what it means only when both operands are positive.
The evaluated result is a double value. For example, 8.27 % 2 evaluates to 0.27 since the division is 4 with a remainder of 0.27.
Of course, both values could be double, so 6.7 % 2.1 evaluates to 0.4 since the division is 3 with a remainder of 0.4. The remainder is computed by assuming the division yields an integer result, with the rest being a remainder.
If that's not obvious, then think it over, and see why it is.
The actual expression is: x % 2 == 0.
When this evaluates to true, x is even, otherwise it's odd.
Testing for oddness is just as easy: x % 2 == 1.
This just says that a number is odd if the remainder after dividing by 2 is 1.
We could equivalently write: x % 2 != 0.
In other words, x is odd when it is not even.