How to Check If a Number Is Divisible by Another Number in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to check if one number is divisible by another in Java. We will explore the use of the modulo operator (%) to determine divisibility by checking if the remainder of a division is zero.

You will practice using the modulo operator with different numbers and divisors, and also learn how to handle the special case of division by zero to prevent errors in your Java programs.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["Object-Oriented and Advanced Concepts"]) java(("Java")) -.-> java/BasicSyntaxGroup(["Basic Syntax"]) java/BasicSyntaxGroup -.-> java/operators("Operators") java/BasicSyntaxGroup -.-> java/variables("Variables") java/BasicSyntaxGroup -.-> java/if_else("If...Else") java/BasicSyntaxGroup -.-> java/output("Output") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/exceptions("Exceptions") subgraph Lab Skills java/operators -.-> lab-559961{{"How to Check If a Number Is Divisible by Another Number in Java"}} java/variables -.-> lab-559961{{"How to Check If a Number Is Divisible by Another Number in Java"}} java/if_else -.-> lab-559961{{"How to Check If a Number Is Divisible by Another Number in Java"}} java/output -.-> lab-559961{{"How to Check If a Number Is Divisible by Another Number in Java"}} java/exceptions -.-> lab-559961{{"How to Check If a Number Is Divisible by Another Number in Java"}} end

Use Modulo for Divisibility

In this step, we will explore how to use the modulo operator (%) in Java to check for divisibility. The modulo operator gives you the remainder of a division. If the remainder of a division is 0, it means the number is perfectly divisible by the divisor.

Let's create a new Java program to demonstrate this.

  1. Open the ~/project directory in the File Explorer on the left.

  2. Right-click in the empty space within the ~/project directory and select "New File".

  3. Name the new file DivisibilityCheck.java.

  4. Open the DivisibilityCheck.java file in the Code Editor.

  5. Copy and paste the following code into the editor:

    public class DivisibilityCheck {
        public static void main(String[] args) {
            int number = 10;
            int divisor = 2;
    
            // Use the modulo operator to check for divisibility
            if (number % divisor == 0) {
                System.out.println(number + " is divisible by " + divisor);
            } else {
                System.out.println(number + " is not divisible by " + divisor);
            }
    
            number = 11;
            divisor = 3;
    
            if (number % divisor == 0) {
                System.out.println(number + " is divisible by " + divisor);
            } else {
                System.out.println(number + " is not divisible by " + divisor);
            }
        }
    }

    Let's look at the new parts:

    • int number = 10;: This declares an integer variable named number and assigns it the value 10.
    • int divisor = 2;: This declares an integer variable named divisor and assigns it the value 2.
    • number % divisor: This is the modulo operation. It calculates the remainder when number is divided by divisor.
    • if (number % divisor == 0): This is an if statement. It checks if the result of the modulo operation is equal to 0. If it is, the code inside the if block is executed.
    • else: If the condition in the if statement is false (the remainder is not 0), the code inside the else block is executed.
  6. Save the file (Ctrl+S or Cmd+S).

  7. Open the Terminal at the bottom of the WebIDE. Ensure you are in the ~/project directory. If not, type cd ~/project and press Enter.

  8. Compile the Java program by typing the following command and pressing Enter:

    javac DivisibilityCheck.java

    If there are no errors, you will not see any output. A DivisibilityCheck.class file will be created in the ~/project directory.

  9. Run the compiled Java program by typing the following command and pressing Enter:

    java DivisibilityCheck

    You should see the following output:

    10 is divisible by 2
    11 is not divisible by 3

This output confirms that our program correctly used the modulo operator to check for divisibility.

Test with Different Divisors

In the previous step, we checked the divisibility of 10 by 2 and 11 by 3. Now, let's modify our program to test with different numbers and divisors to see how the modulo operator behaves.

  1. Open the DivisibilityCheck.java file in the WebIDE editor if it's not already open.

  2. Let's add a few more examples to the main method. Add the following lines of code before the closing curly brace } of the main method:

            System.out.println("\nTesting with different numbers:");
    
            number = 15;
            divisor = 5;
            if (number % divisor == 0) {
                System.out.println(number + " is divisible by " + divisor);
            } else {
                System.out.println(number + " is not divisible by " + divisor);
            }
    
            number = 20;
            divisor = 7;
            if (number % divisor == 0) {
                System.out.println(number + " is divisible by " + divisor);
            } else {
                System.out.println(number + " is not divisible by " + divisor);
            }
    
            number = 100;
            divisor = 10;
            if (number % divisor == 0) {
                System.out.println(number + " is divisible by " + divisor);
            } else {
                System.out.println(number + " is not divisible by " + divisor);
            }

    We've added three new checks with different values for number and divisor. The System.out.println("\nTesting with different numbers:"); line simply adds a blank line and a heading to make the output clearer.

  3. Save the modified DivisibilityCheck.java file (Ctrl+S or Cmd+S).

  4. Open the Terminal and make sure you are in the ~/project directory.

  5. Compile the updated Java program:

    javac DivisibilityCheck.java

    Again, if the compilation is successful, you won't see any output.

  6. Run the compiled program to see the results with the new test cases:

    java DivisibilityCheck

    You should now see the output from the previous step, followed by the output from the new test cases:

    10 is divisible by 2
    11 is not divisible by 3
    
    Testing with different numbers:
    15 is divisible by 5
    20 is not divisible by 7
    100 is divisible by 10

By adding these test cases, you can see how the modulo operator correctly identifies whether a number is perfectly divisible by another number. This is a fundamental concept used in many programming tasks, such as checking for even or odd numbers, or performing actions at regular intervals.

Handle Division by Zero

In mathematics, division by zero is undefined. In programming, attempting to divide by zero (or perform a modulo operation with zero as the divisor) will typically cause an error. It's important to handle this situation in your code to prevent your program from crashing.

Let's modify our DivisibilityCheck.java program to include a check for division by zero.

  1. Open the DivisibilityCheck.java file in the WebIDE editor.

  2. We will add a new test case where the divisor is 0. Add the following code before the closing curly brace } of the main method:

            System.out.println("\nTesting division by zero:");
    
            number = 10;
            divisor = 0;
    
            if (divisor == 0) {
                System.out.println("Error: Division by zero is not allowed.");
            } else if (number % divisor == 0) {
                System.out.println(number + " is divisible by " + divisor);
            } else {
                System.out.println(number + " is not divisible by " + divisor);
            }

    Here's what we added:

    • if (divisor == 0): This is a new if statement that checks if the divisor variable is equal to 0.
    • System.out.println("Error: Division by zero is not allowed.");: If the divisor is 0, this line prints an error message.
    • else if (number % divisor == 0): This is an else if statement. It's checked only if the first if condition (divisor == 0) is false. This is where we perform the modulo check, but only if the divisor is not zero.
  3. Save the modified DivisibilityCheck.java file.

  4. Open the Terminal and ensure you are in the ~/project directory.

  5. Compile the updated Java program:

    javac DivisibilityCheck.java
  6. Run the compiled program:

    java DivisibilityCheck

    You should see the output from the previous steps, followed by the output for the division by zero test case:

    10 is divisible by 2
    11 is not divisible by 3
    
    Testing with different numbers:
    15 is divisible by 5
    20 is not divisible by 7
    100 is divisible by 10
    
    Testing division by zero:
    Error: Division by zero is not allowed.

By adding the if (divisor == 0) check, we've made our program more robust by preventing a potential error when the divisor is zero. This is an important aspect of writing reliable code.

Summary

In this lab, we learned how to check if a number is divisible by another number in Java using the modulo operator (%). We created a Java program DivisibilityCheck.java and used the if statement to check if the remainder of the division (number % divisor) is equal to 0. If the remainder is 0, the number is divisible by the divisor. We demonstrated this with examples where the number is divisible and where it is not.