Write a Java Program to Check Whether a Number is Prime or Not

As a Java programmer, one of the fundamental problems is determining whether a number is prime or not.

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.

In other words, a number is prime if it is only divisible by 1 and itself.


To check whether a number is prime or not in Java, we can use a simple algorithm.

We start by checking if the number is divisible by 2 or 3, since all prime numbers greater than 3 are of the form 6n ± 1.

If the number is not divisible by 2 or 3, we can then check whether it is divisible by any odd number greater than 3 up to the square root of the number.

Here’s a Java program to check whether a number is prime or not:

import java.util.Scanner;

public class PrimeNumber {

   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.print("Enter a number: ");
      int num = sc.nextInt();
      boolean isPrime = true;
      if (num < 2) {
         isPrime = false;
      } else {
         for (int i = 2; i <= Math.sqrt(num); i++) {
            if (num % i == 0) {
               isPrime = false;
               break;
            }
         }
      }
      if (isPrime) {
         System.out.println(num + " is a prime number");
      } else {
         System.out.println(num + " is not a prime number");
      }
   }
}

In this program, we first take user input using the Scanner class.

We then initialize a boolean variable isPrime to true. If the input number is less than 2, we set isPrime to false since all prime numbers are greater than 1.

Otherwise, we iterate through all odd numbers greater than or equal to 2 and less than or equal to the square root of the input number.

If the input number is divisible by any of these numbers, we set isPrime to false and break out of the loop.

Finally, we check the value of isPrime and print the appropriate message to the console.


In conclusion, checking whether a number is prime or not is a common task in programming, and it’s essential to have an efficient algorithm for doing so.

By using the above Java program, you can quickly determine whether a given number is prime or not.