What's the syntax for mod in java

Bob picture Bob · Sep 18, 2008 · Viewed 949.3k times · Source

As an example in pseudocode:

if ((a mod 2) == 0)
{
    isEven = true;
}
else
{
    isEven = false;
}

Answer

Cody Hatch picture Cody Hatch · Sep 18, 2008

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;