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 OverflowVideos
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;
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.
I have a test tomorrow, in the test one of the questions will be to seperate a number from a 3 digit number, say I have 641, I need to know how to print out 6,4 and 1 seperately.
What the hell do I do ? The teacher is so bad I couldn't understand a word she said and neither did my class, we already complained about her but this isn't the issue, the issue is that I have no easy answers on the internet for what the modulo is.
Why does doing (n/100)%10; print out the hundred digit ? I have no idea how this works, please go easy on me.
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.