[java] What's the syntax for mod in java

As an example in pseudocode:

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

This question is related to java modulo

The answer is


if (a % 2 == 0) {
} else {
}

you should examine the specification before using 'remainder' operator % :

http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.17.3

// bad enough implementation of isEven method, for fun. so any worse?
boolean isEven(int num)
{
    num %= 10;
    if(num == 1)
       return false;
    else if(num == 0)
       return true;
    else
       return isEven(num + 2);
}
isEven = isEven(a);

While it's possible to do a proper modulo by checking whether the value is negative and correct it if it is (the way many have suggested), there is a more compact solution.

(a % b + b) % b

This will first do the modulo, limiting the value to the -b -> +b range and then add b in order to ensure that the value is positive, letting the next modulo limit it to the 0 -> b range.

Note: If b is negative, the result will also be negative


An alternative to the code from @Cody:

Using the modulus operator:

bool isEven = (a % 2) == 0;

I think this is marginally better code than writing if/else, because there is less duplication & unused flexibility. It does require a bit more brain power to examine, but the good naming of isEven compensates.


Another way is:

boolean isEven = false;
if((a % 2) == 0)
{
    isEven = true;
}

But easiest way is still:

boolean isEven = (a % 2) == 0;

Like @Steve Kuo said.


Since everyone else already gave the answer, I'll add a bit of additional context. % the "modulus" operator is actually performing the remainder operation. The difference between mod and rem is subtle, but important.

(-1 mod 2) would normally give 1. More specifically given two integers, X and Y, the operation (X mod Y) tends to return a value in the range [0, Y). Said differently, the modulus of X and Y is always greater than or equal to zero, and less than Y.

Performing the same operation with the "%" or rem operator maintains the sign of the X value. If X is negative you get a result in the range (-Y, 0]. If X is positive you get a result in the range [0, Y).

Often this subtle distinction doesn't matter. Going back to your code question, though, there are multiple ways of solving for "evenness".

The first approach is good for beginners, because it is especially verbose.

// Option 1: Clearest way for beginners
boolean isEven;
if ((a % 2) == 0)
{
  isEven = true
}
else
{
  isEven = false
}

The second approach takes better advantage of the language, and leads to more succinct code. (Don't forget that the == operator returns a boolean.)

// Option 2: Clear, succinct, code
boolean isEven = ((a % 2) == 0);

The third approach is here for completeness, and uses the ternary operator. Although the ternary operator is often very useful, in this case I consider the second approach superior.

// Option 3: Ternary operator
boolean isEven = ((a % 2) == 0) ? true : false;

The fourth and final approach is to use knowledge of the binary representation of integers. If the least significant bit is 0 then the number is even. This can be checked using the bitwise-and operator (&). While this approach is the fastest (you are doing simple bit masking instead of division), it is perhaps a little advanced/complicated for a beginner.

// Option 4: Bitwise-and
boolean isEven = ((a & 1) == 0);

Here I used the bitwise-and operator, and represented it in the succinct form shown in option 2. Rewriting it in Option 1's form (and alternatively Option 3's) is left as an exercise to the reader. ;)

Hope that helps.


The code runs much faster without using modulo:

public boolean isEven(int a){
    return ( (a & 1) == 0 );
}

public boolean isOdd(int a){
    return ( (a & 1) == 1 );
}

if (a % 2 == 0) {
} else {
}

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.


Also, mod can be used like this:

int a = 7;
b = a % 2;

b would equal 1. Because 7 % 2 = 1.


An alternative to the code from @Cody:

Using the modulus operator:

bool isEven = (a % 2) == 0;

I think this is marginally better code than writing if/else, because there is less duplication & unused flexibility. It does require a bit more brain power to examine, but the good naming of isEven compensates.


To get Java's % (REM) operation to work like MOD for negative X and positive Y values, you can use this method:

private int mod(int x, int y)
{
    int result = x % y;
    if (result < 0)
    {
        result += y;
    }
    return result;
}

or with the ternary operator (shorter, but not possible or less efficient in some situations):

private int mod(int x, int y)
{
    int result = x % y;
    return result < 0? result + y : result;
}

Java actually has no modulo operator the way C does. % in Java is a remainder operator. On positive integers, it works exactly like modulo, but it works differently on negative integers and, unlike modulo, can work with floating point numbers as well. Still, it's rare to use % on anything but positive integers, so if you want to call it a modulo, then feel free!


In Java it is the % operator: 15.17.3. Remainder Operator %

Note that there is also floorMod in the java.lang.Math class which will give a different result from % for arguments with different signs:

public static int floorMod?(int x, int y)


The remainder operator in Java is % and the modulo operator can be expressed as

public int mod(int i, int j)
{
  int rem = i % j;
  if (j < 0 && rem > 0)
  {
    return rem + j;
  }
  if (j > 0 && rem < 0)
  {
    return rem + j;
  }
  return rem;
}

An alternative to the code from @Cody:

Using the modulus operator:

bool isEven = (a % 2) == 0;

I think this is marginally better code than writing if/else, because there is less duplication & unused flexibility. It does require a bit more brain power to examine, but the good naming of isEven compensates.


The modulo operator is % (percent sign). To test for evenness or generally do modulo for a power of 2, you can also use & (the and operator) like isEven = !( a & 1 ).


Also, mod can be used like this:

int a = 7;
b = a % 2;

b would equal 1. Because 7 % 2 = 1.


The modulo operator is % (percent sign). To test for evenness or generally do modulo for a power of 2, you can also use & (the and operator) like isEven = !( a & 1 ).


As others have pointed out, the % (remainder) operator is not the same as the mathematical mod modulus operation/function.

mod vs %

The x mod n function maps x to n in the range of [0,n).
Whereas the x % n operator maps x to n in the range of (-n,n).

In order to have a method to use the mathematical modulus operation and not care about the sign in front of x one can use:

((x % n) + n) % n

Maybe this picture helps understand it better (I had a hard time wrapping my head around this first)

enter image description here


Java actually has no modulo operator the way C does. % in Java is a remainder operator. On positive integers, it works exactly like modulo, but it works differently on negative integers and, unlike modulo, can work with floating point numbers as well. Still, it's rare to use % on anything but positive integers, so if you want to call it a modulo, then feel free!


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.


In Java, the mod operation can be performed as such:

Math.floorMod(a, b)

Note: The mod operation is different from the remainder operation. In Java, the remainder operation can be performed as such:

a % b

In Java it is the % operator: 15.17.3. Remainder Operator %

Note that there is also floorMod in the java.lang.Math class which will give a different result from % for arguments with different signs:

public static int floorMod?(int x, int y)


Since everyone else already gave the answer, I'll add a bit of additional context. % the "modulus" operator is actually performing the remainder operation. The difference between mod and rem is subtle, but important.

(-1 mod 2) would normally give 1. More specifically given two integers, X and Y, the operation (X mod Y) tends to return a value in the range [0, Y). Said differently, the modulus of X and Y is always greater than or equal to zero, and less than Y.

Performing the same operation with the "%" or rem operator maintains the sign of the X value. If X is negative you get a result in the range (-Y, 0]. If X is positive you get a result in the range [0, Y).

Often this subtle distinction doesn't matter. Going back to your code question, though, there are multiple ways of solving for "evenness".

The first approach is good for beginners, because it is especially verbose.

// Option 1: Clearest way for beginners
boolean isEven;
if ((a % 2) == 0)
{
  isEven = true
}
else
{
  isEven = false
}

The second approach takes better advantage of the language, and leads to more succinct code. (Don't forget that the == operator returns a boolean.)

// Option 2: Clear, succinct, code
boolean isEven = ((a % 2) == 0);

The third approach is here for completeness, and uses the ternary operator. Although the ternary operator is often very useful, in this case I consider the second approach superior.

// Option 3: Ternary operator
boolean isEven = ((a % 2) == 0) ? true : false;

The fourth and final approach is to use knowledge of the binary representation of integers. If the least significant bit is 0 then the number is even. This can be checked using the bitwise-and operator (&). While this approach is the fastest (you are doing simple bit masking instead of division), it is perhaps a little advanced/complicated for a beginner.

// Option 4: Bitwise-and
boolean isEven = ((a & 1) == 0);

Here I used the bitwise-and operator, and represented it in the succinct form shown in option 2. Rewriting it in Option 1's form (and alternatively Option 3's) is left as an exercise to the reader. ;)

Hope that helps.


In Java, the mod operation can be performed as such:

Math.floorMod(a, b)

Note: The mod operation is different from the remainder operation. In Java, the remainder operation can be performed as such:

a % b

you should examine the specification before using 'remainder' operator % :

http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.17.3

// bad enough implementation of isEven method, for fun. so any worse?
boolean isEven(int num)
{
    num %= 10;
    if(num == 1)
       return false;
    else if(num == 0)
       return true;
    else
       return isEven(num + 2);
}
isEven = isEven(a);

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.


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.


The code runs much faster without using modulo:

public boolean isEven(int a){
    return ( (a & 1) == 0 );
}

public boolean isOdd(int a){
    return ( (a & 1) == 1 );
}

Also, mod can be used like this:

int a = 7;
b = a % 2;

b would equal 1. Because 7 % 2 = 1.


An alternative to the code from @Cody:

Using the modulus operator:

bool isEven = (a % 2) == 0;

I think this is marginally better code than writing if/else, because there is less duplication & unused flexibility. It does require a bit more brain power to examine, but the good naming of isEven compensates.


As others have pointed out, the % (remainder) operator is not the same as the mathematical mod modulus operation/function.

mod vs %

The x mod n function maps x to n in the range of [0,n).
Whereas the x % n operator maps x to n in the range of (-n,n).

In order to have a method to use the mathematical modulus operation and not care about the sign in front of x one can use:

((x % n) + n) % n

Maybe this picture helps understand it better (I had a hard time wrapping my head around this first)

enter image description here


The remainder operator in Java is % and the modulo operator can be expressed as

public int mod(int i, int j)
{
  int rem = i % j;
  if (j < 0 && rem > 0)
  {
    return rem + j;
  }
  if (j > 0 && rem < 0)
  {
    return rem + j;
  }
  return rem;
}

if (a % 2 == 0) {
} else {
}

The modulo operator is % (percent sign). To test for evenness or generally do modulo for a power of 2, you can also use & (the and operator) like isEven = !( a & 1 ).


Another way is:

boolean isEven = false;
if((a % 2) == 0)
{
    isEven = true;
}

But easiest way is still:

boolean isEven = (a % 2) == 0;

Like @Steve Kuo said.


The modulo operator is % (percent sign). To test for evenness or generally do modulo for a power of 2, you can also use & (the and operator) like isEven = !( a & 1 ).