Instead of the modulo operator, which has slightly different semantics, for non-negative integers, you can use the remainder operator %. For your exact example:
if ((a % 2) == 0)
{
isEven = true;
}
else
{
isEven = false;
}
This can be simplified to a one-liner:
isEven = (a % 2) == 0;
Answer from Cody Hatch on Stack OverflowInstead of the modulo operator, which has slightly different semantics, for non-negative integers, you can use the remainder operator %. For your exact example:
if ((a % 2) == 0)
{
isEven = true;
}
else
{
isEven = false;
}
This can be simplified to a one-liner:
isEven = (a % 2) == 0;
Here is the representation of your pseudo-code in minimal Java code;
boolean isEven = a % 2 == 0;
I'll now break it down into its components. The modulus operator in Java is the percent character (%). Therefore taking an int % int returns another int. The double equals (==) operator is used to compare values, such as a pair of ints and returns a boolean. This is then assigned to the boolean variable 'isEven'. Based on operator precedence the modulus will be evaluated before the comparison.
Videos
number % 2 is an expression that can't be evaluated to a boolean by any means.
15.17.3. Remainder Operator %
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.
https://docs.oracle.com/javase/specs/jls/se12/html/jls-15.html#jls-15.17.3
The modulus operator returns an int, in this case but it could return a double or long depending on the operands. An if statement requires a boolean. So the reason why you can't do if(number % 2) is because there is no boolean. With if(number % 2 == 0) you are checking if the result of the modulo operator is zero, which is a boolean.