I'd like to ask about using the modulus operation, could someone tell me how to use an if statement, why use [== 0], but we can assign the value from a modulus calculation into another variable.

Why does below code work?

 int number = 100;if(number % 2 == 0){sout(number);}

and why does this one also work not using if?

lastDigit = number % 10;

why doesn't below statement work?

if(number % 2){sout (number);} 
2

Best Answer


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.