Google Advertisement

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

Google Advertisement
πŸ”₯ Read with Full Features on Our Website

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.

Published on 02 May 2025
By Vandu

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?

πŸ”₯ Read with Full Features on Our Website

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

βœ… Examples of Prime Numbers:

❌ Not Prime:


🧾 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;
    }
}

βœ… 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).

Google Advertisement

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


πŸ“Œ Conclusion

You have now learned:

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

 

❀️ Like πŸ’¬ Comment πŸ”— Share
Google Advertisement
πŸ‘‰ View Full Version on Main Website β†—
Google Advertisement
πŸ‘‰ Read Full Article on Website