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.
How does the modulus operator work?
Using the modulo operator in java - Stack Overflow
What is the difference between modulus and divide symbol in java(% and /)? | Core Java Forum
The Modulus Operator is Powerful!
Videos
I apologise in advance if this is a stupid question, but I've looked everywhere and every explanation I've found has been way above my pay grade.
I've been studying java for a grand total of one week. My lecturer gave us notes that cover the modulus, but after reading them I'm still none the wiser. The examples he gives don't seem consistent and I'm just getting more and more confused.
The exercise involves trying convert 174 pounds into stone and pounds using the modulus, but I honestly have no idea where the modulus goes or how it works, or what numbers I'm supposed to put where. I'd be grateful for literally any explanation at this point.
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.