Home » Core Java » Java Modulus Example

About Petros Koulianos

Petros Koulianos
Petros studied Computer Science in Hellenic Open University . He is an experienced administrator with a demonstrated history of working in the health information technology systems and health services industry. Skilled in Oracle Databases, HL7 Standards, Health Information Systems (HIS), Laboratory Information Systems (LIS) . In his free time designs and develop apps in Java , Android and node.js .

Java Modulus Example

In this post, we feature a comprehensive article about Java Modulus.

1. Introduction

This article will show the usage of the modulo operation that computes the remainder after division of 2 numbers. Java use a specific arithmetic operator the Remainder Operator with the symbol %.

2. Java Modulus – Use Cases

In this section we show same useful use cases .

2.1 Basic Usage

Create a class with name ModulusExample1 and paste the following code :

ModulusExample1.java
package com.javacodegeeks;

/**
 * @author Petros Koulianos
 *
 */
public class ModulusExample1 {


	public static void main(String[] args) {
		
		int x = 3;
		int z = 10;
		int y = -23;		
		int w = -12;
		double d = 2.15;
		float f= 3.6f;
		int zero=0;
		
		//positive number modulus positive number
		//the result is the remainder of the division 
		System.out.println("positive number modulus positive int number: "+z % x);
		
		System.out.println("positive number modulus positive double number: "+z % d);
		
		System.out.println("positive number modulus positive float number: "+z % f);
		
		//negative number modulus positive number
		//the result is negative
		System.out.println("negative number modulus positive number: "+ y % z);
		
		//negative number modulus negative number
		//the result is the negative remainder of the division 
		System.out.println("negative number modulus negative number: "+w % y);
		
		//zero number modulus  number
	    //the result is zero
		System.out.println("zero modulus number : "+zero % z);
		
		// number modulus zero
		//throws java.lang.ArithmeticException , it must surround with try catch brackets
		//in order to avoid crush the execution
		try {
			
			System.out.println("number modulus zero : "+z % zero);
			
		}catch(ArithmeticException e) {
			//print stack trace
			e.printStackTrace();
			
		}
		


	}

}
Console Output
positive number modulus positive int number: 1
positive number modulus positive double number: 1.4000000000000004
positive number modulus positive float number: 2.8000002
negative number modulus positive number: -3
negative number modulus negative number: -12
zero modulus number : 0
java.lang.ArithmeticException: / by zero
	at com.javacodegeeks.ModulusExample1.main(ModulusExample1.java:48)

2.2 Find if a number is odd or even

Create a class with name ModulusExample2 and paste the following code :

ModulusExample2.java
package com.javacodegeeks;
/**
 * @author Petros Koulianos
 *
 */
public class ModulusExample2 {

	public static void main(String[] args) {
		
		// find out when a number is even or odd
		for(int i=0 ; i<=10000; i++) {
			//modulus each number with 2
			if(i % 2 == 0) {
				//number is even
				System.out.println("number "+i+" is even");
			}else {
				//number is odd
				System.out.println("number "+i+" is odd");
			}
						
		}

	}
}

The most noteworthy case to use the modulo operation is to find if a given number is even or odd . The above code run a loop to check the numbers if it is odd or even , by modulus each number by 2.

2.3 Perform an action at nth number of times in loop

Create a class with name ModulusExample3 and paste the following code :

ModulusExample3.java
package com.javacodegeeks;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Petros Koulianos
 *
 */

public class ModulusExample3 {

	public static void main(String[] args) {

		// perform an action at n-th number of loops
		List bigList = getList();
		int n = 1000; // n-th times 
		for (int i = 0; i < bigList.size(); i++) {
			// check the process of the running list every 1000 loops
			if (i % n == 0) {
				// calculate the process of the running list
				double process = (100 * i) / bigList.size();
				// you can update your UI with a process bar
				System.out.println("process " + process + "%");
			}

		}
		// your list ended
		System.out.println("process 100.0%");
	}

	// method to generate a list, simulating a very large dataset
	// from database or file(csv , xml etc) or web service (json etc)
	public static List getList() {
		List list = new ArrayList();
		for (int i = 0; i < 98562; i++) {
			double x =  Math.random();
			list.add(x * 1000);
		}
		return list;
	}
}
Console Output
process 0.0%
process 1.0%
process 2.0%
...
...
...
process 98.0%
process 99.0%
process 100.0%

2.4 Find the greatest common divisor

The euclidian algorithm uses the modulo operation , in order to find the greatest common division.

Create a class with name ModulusExample4 and paste the following code :

ModulusExample4.java
package com.javacodegeeks;

/**
 * @author Petros Koulianos
 *
 */

public class ModulusExample4 {

	public static void main(String[] args) {
		// This example implements the Euclidean algorithm from
		//https://en.wikipedia.org/wiki/Euclidean_algorithm#Implementations

		int a = 1071;
		int b = 462;
		int temp ;

		while (b != 0) {
			temp = b;
			b = a % b;
			a = temp;
		}
		
		System.out.println("The Greatest Common Division is "+a);
	}

}
Console Output
The Greatest Common Division is 21

2.5 Find out if an integer is prime number.

Another usage of modulo operation is in the algorithm of prime numbers .

Create a class with name ModulusExample5 and paste the following code :

ModulusExample5.java
package com.javacodegeeks;
/**
 * @author Petros Koulianos
 *
 */
public class ModulusExample5 {


	public static void main(String[] args) {
		//This example implements prime number algorithm
		//from https://en.wikipedia.org/wiki/Prime_number#Computational_methods
		
		int x = 28 ; 
		int y = 113;
		
		int temp1 = 0;
		int temp2 = 0;
		
		// run a loop from 2 to square root x
        for(int i=2 ; i <= Math.sqrt(x); i++) {
        	
            if(x % i == 0) {
                // i number can multiply x
            	temp1 ++;
            }      
        }
        
     // run a loop from 2 to square root y
        for(int i=2 ; i <= Math.sqrt(y); i++) {

            if(y % i == 0) {
                // i number can multiply y
            	temp2 ++;
            }            
        }
        
        // if x or y has zero multipliers is prime 
        if(temp1 == 0) {
        	System.out.println("number "+x+" is prime");
        }else {
        	System.out.println("number "+x+" is not prime");
        }
        if(temp2 == 0) {
        	System.out.println("number "+y+" is prime");
        }else {
        	System.out.println("number "+y+" is not prime");
        }
	}

}

Console Output
number 28 is not prime
number 113 is prime

3. Download the Source Code

This was an example about how to use the Java Modulus ( Remainder Operator ).

Download
You can download the full source code of this example here: Java Modulus Example
(+3 rating, 3 votes)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of