Java Modulus Division

Java Modulus Arithmetic operator takes two operands as inputs and returns the reminder of division of left operand by right operand.

% symbol is used for Modulus Division Operator.

Syntax – Modulus Division Operator

Following is the syntax for Modulus Division Operator.

</>
Copy
result = operand_1 % operand_2

The operands could be of any numeric datatype.

If the two operands are of different datatypes, implicit datatype promotion takes place and value of lower datatype is promoted to higher datatype.

Example 1 – Modulus Division of two Integers

In the following example, we shall take two integers and apply Modulus Division operation to find the reminder of division operation.

Java Program

</>
Copy
public class ModulusExample {
	public static void main(String[] args) {
		int a = 7;
		int b = 3;
		
		int result = a % b;
		System.out.print(result);
	}
}

Output

1

Example 2 – Modulus Division of two Numbers belonging to Different Datatypes

In the following example, we shall find the Modular division of an integer with a float using Modulus Arithmetic Operator.

As the operand values are of two different datatypes, Java promotes the value with lower datatype to higher datatype and the result would be of higher datatype. In the following example, int is promoted to float, and the result is a floating point number.

Java Program

</>
Copy
public class ModulusExample {
	public static void main(String[] args) {
		int a = 7;
		float b = 3.1f;
		
		float result = a % b;
		System.out.print(result);
	}
}

Output

0.8000002

Conclusion

In this Java Tutorial, we learned how to use Java Modulus Operator.