Please login


Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

Java Program to Check Whether a Number is Prime or Not

Java program to check whether the number is prime number or not :


Prime Number are the whole numbers which have two factors i.e. 1 and the number by itself. Some of the facts for the prime numbers are given below :-

  • 0 and 1 are not considered as prime number.
  • Except for 0 and 1, a number is either a prime number or a composite number.
  • Numbers that have more than two factors are called composite numbers.
  • The  1 is neither prime nor composite.
  • Except 2, all other even numbers are not prime.

The first 25 prime numbers (all the prime numbers less than 100) are : 2, 3, 5, 7, 11, 13, 17, 19, 23
29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97.

Working :

Step 1 – Ask the user to enter a number.

Step 2 – Set  count = 0.

Step 3 – Create a loop of i from 1 to number n and increase the value of i after every iteration by 1.

Step 4 – Calculate mod(%) of n by every value of i and check whether the calculated value is equal to 0 or not.

Step 5 – If step-4 gets true then, increase the value of count by 1 and move to the step-3 until the test condition get false.

Step 6 – After getting out of the loop check the value of count is equal to 2 or not.

Step 7- If the value of count is equal to 2 then , the number is Prime, else ,number is not prime.

Step 8 – Print the result.

Code in Java :

//JAVA Program to check whether the number entered by user is Prime or not.
import java.util.Scanner;
public class prime
{ //class declaration
public static void main(String[] args)
{ //main method declaration
Scanner sc=new Scanner(; //scanner class object creation

System.out.println("Enter a number");
int n = sc.nextInt(); //taking a number n as input
int count=0;
for(int i = 1 ; i <=n ; i++)
if(n % i == 0) //condition for getting the factors of number n
if(count == 2) //if factors are two then, number is prime else not
System.out.println("Prime Number");
System.out.println("Not a Prime Number");
sc.close(); //closing scanner class(not mandatory but good practice)
} //end of main method
} //end of class

Output :

Enter a number
Not a Prime Number

Enter a number
Prime Number

Enter a number
Prime Number