How to Check Prime Numbers in Java with Easy Code & Explanation

By Vandu
May 2, 2025

Follow us on


Learn how to write a Java program to check if a number is prime. Step-by-step explanation, beginner-friendly code, and best practices for Java programming.

How to Check Prime Numbers in Java with Easy Code & Explanation

Write a Program to Check if a Number is Prime in Java

In this tutorial, you will learn how to write a Java program to check whether a number is prime or not. Weโ€™ll go through everything step-by-step, with simple explanations and a beginner-friendly approach.


๐Ÿง What is a Prime Number?

A prime number is a natural number greater than 1 that has only two factors: 1 and itself.

โœ… Examples of Prime Numbers:

  • 2, 3, 5, 7, 11, 13...

โŒ Not Prime:

  • 1 (has only one factor)

  • 4 (has three factors: 1, 2, 4)

  • 9 (has three factors: 1, 3, 9)


๐Ÿงพ Java Program to Check if a Number is Prime

import java.util.Scanner;

public class PrimeCheck {
    public static void main(String[] args) {
        // Step 1: Create a Scanner object to get input from the user
        Scanner sc = new Scanner(System.in);

        // Step 2: Ask the user to enter a number
        System.out.print("Enter a number: ");
        int num = sc.nextInt();

        // Step 3: Handle edge cases
        if (num <= 1) {
            System.out.println(num + " is not a prime number.");
        } else {
            boolean isPrime = true;

            // Step 4: Check divisibility from 2 to square root of the number
            for (int i = 2; i <= Math.sqrt(num); i++) {
                if (num % i == 0) {
                    isPrime = false;
                    break;
                }
            }

            // Step 5: Print result
            if (isPrime) {
                System.out.println(num + " is a prime number.");
            } else {
                System.out.println(num + " is not a prime number.");
            }
        }

        // Step 6: Close the Scanner
        sc.close();
    }
}

๐Ÿงต Step-by-Step Explanation:

โœ… Step 1: Import Scanner Class

import java.util.Scanner;

We need Scanner to read user input.


โœ… Step 2: Take Input from the User

Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();

We prompt the user to enter a number and store it in variable num.


โœ… Step 3: Handle Special Cases

if (num <= 1) {
    System.out.println(num + " is not a prime number.");
}

We check if the number is less than or equal to 1. These are not prime numbers.


โœ… Step 4: Check for Divisibility

for (int i = 2; i <= Math.sqrt(num); i++) {
    if (num % i == 0) {
        isPrime = false;
        break;
    }
}
  • We loop from 2 to the square root of the number.

  • If any number divides num evenly (num % i == 0), then it's not prime.

  • We use Math.sqrt(num) for better performance (instead of checking up to num - 1).


โœ… Step 5: Display the Result

if (isPrime) {
    System.out.println(num + " is a prime number.");
} else {
    System.out.println(num + " is not a prime number.");
}

โœ… Step 6: Close Scanner

sc.close();

Always close the Scanner object to avoid memory leaks.


๐ŸŽฏ Sample Output:

Enter a number: 7
7 is a prime number.

Enter a number: 12
12 is not a prime number.

Enter a number: 1
1 is not a prime number.

๐Ÿš€ Why Use Math.sqrt(num) in the Loop?

Because if a number n is divisible by some number a, then it is also divisible by b = n/a. So, if a <= sqrt(n), then b >= sqrt(n).

By checking only up to sqrt(n), we can reduce the number of operations, making the program more efficient.


๐Ÿ“Œ Conclusion

You have now learned:

  • What a prime number is

  • How to take input in Java

  • How to check if a number is prime using a for loop

  • Why we use Math.sqrt(num) for optimization

This is a very important concept for Java beginners and is often asked in interviews and coding tests.

 


ยฉ 2025 Pay18News. All rights reserved.