Write a Java Program to Display Factors of a Number

Java is an object-oriented programming language that is widely used for developing various applications.

In this tutorial, we will discuss how to write a Java program to display factors of a number.


Factors of a number are the numbers that divide the given number completely without leaving any remainder.

For example, the factors of 12 are 1, 2, 3, 4, 6, and 12.

To display factors of a number in Java, we will use a for loop to iterate through all the numbers from 1 to the given number.

We will then check whether the current number is a factor of the given number by dividing the given number by the current number and checking if the remainder is 0.

If the remainder is 0, then the current number is a factor of the given number.

Let’s take a look at the code for displaying factors of a number in Java:

import java.util.Scanner;

public class FactorOfNumber {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.print("Enter a number: ");
      int number = sc.nextInt();
      System.out.print("Factors of " + number + " are: ");
      for(int i = 1; i <= number; i++) {
         if(number % i == 0) {
            System.out.print(i + " ");
         }
      }
      sc.close();
   }
}

In the above code, we first import the Scanner class from the java.util package to get input from the user.

We then create an object of the Scanner class and ask the user to enter a number.

We store the input number in the ‘number’ variable.

We then use a for loop to iterate through all the numbers from 1 to the given number.

Inside the loop, we check whether the current number is a factor of the given number by dividing the given number by the current number and checking if the remainder is 0.

If the remainder is 0, then the current number is a factor of the given number, and we display it using the System.out.println() method.

Finally, we close the Scanner object to prevent resource leaks.


In conclusion, displaying factors of a number in Java is a simple task that can be achieved using a for loop and an if statement.

The above code can be used as a reference for writing your own program to display factors of a number in Java.