2

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);
}       
Emma
  • 27,428
  • 11
  • 44
  • 69
ganiyu
  • 65
  • 1
  • 7
  • 4
    You seem to think modulo means "is x divisible by y with no remainder" - it instead means "what's the remainder if I divide x by y". – Michael Berry Aug 04 '19 at 21:51
  • 2
    If you aren't using an IDE (such as IntelliJ or Eclipse), this would be a great time to start. In IntelliJ, this code `if (1 % 2) { }` shows an error: `Incompatible types. Required: boolean Found: int`. – Kaan Aug 04 '19 at 23:22
  • 1
    There is no modulo operator in Java. This s the remainder operator. – user207421 Aug 05 '19 at 00:29
  • Possible duplicate of [What's the syntax for mod in java](https://stackoverflow.com/questions/90238/whats-the-syntax-for-mod-in-java) – 17slim Aug 05 '19 at 16:11

2 Answers2

1

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

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
0

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.

Matt Berteaux
  • 763
  • 4
  • 12