News Blog Fact Check Press Release Jobs Event Product FAQ Local Business Lists Live Music Recipe

How to Check if a Number is Prime Using Java โ€“ Simple Java Code with Full Explanation

Learn how to write a Java program to check if a number is prime. Step-by-step explanation with easy code and logic for beginners and Java learners.

Published on

Introduction

A prime number is a number that is greater than 1 and divisible only by 1 and itself. For example, 2, 3, 5, 7, 11, etc., are prime numbers.

In this blog, we will write a Java program to check whether a given number is prime or not. We will also explain the logic step-by-step so even beginners can understand.


๐Ÿ” What is a Prime Number?

A prime number is a natural number that has exactly two distinct factors:

  1. 1

  2. The number itself

For example:

  • Google Advertisement

    5 is prime because it can only be divided by 1 and 5.

  • 6 is not prime because it is divisible by 1, 2, 3, and 6.


๐Ÿง  Logic to check prime number in Java

Here’s how you can think about the problem:

  1. A number less than or equal to 1 is not a prime.

  2. If a number has a factor other than 1 and itself, it's not a prime.

  3. You only need to check for divisibility up to the square root of the number. (This is for optimization, but we’ll use a simple loop for beginners.)


๐Ÿ’ก Java Code to Check if a Number is Prime

import java.util.Scanner;

public class PrimeCheck {

    public static void main(String[] args) {

        // Step 1: Take input from the user
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int number = scanner.nextInt();

        // Step 2: Call the isPrime function and store result
        boolean result = isPrime(number);

        // Step 3: Show the result to the user
        if (result) {
            System.out.println(number + " is a Prime Number.");
        } else {
            System.out.println(number + " is NOT a Prime Number.");
        }

        scanner.close();
    }

    // Function to check if the number is prime
    public static boolean isPrime(int num) {

        // Numbers less than or equal to 1 are not prime
        if (num <= 1) {
            return false;
        }

        // Check from 2 to num-1
        for (int i = 2; i < num; i++) {
            // If number is divisible by any i, then it's not prime
            if (num % i == 0) {
                return false;
            }
        }

        // If no divisor found, it's a prime number
        return true;
    }
}

๐Ÿ” Step-by-Step Explanation of the Code

โœ… Step 1: Take Input

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
Google Advertisement

We use Scanner class to get user input. The user enters a number which we want to check.


โœ… Step 2: Call the isPrime() Function

boolean result = isPrime(number);

We pass the user input to the function isPrime() which returns true if the number is prime, otherwise false.


โœ… Step 3: Print the Result

if (result) {
    System.out.println(number + " is a Prime Number.");
} else {
    System.out.println(number + " is NOT a Prime Number.");
}

Based on the result from isPrime(), we print the appropriate message.


โœ… Step 4: The isPrime() Function

public static boolean isPrime(int num)

This is a custom function that checks if the given number is prime.

if (num <= 1) {
    return false;
}

Any number less than or equal to 1 is not prime, so we return false.

for (int i = 2; i < num; i++) {
    if (num % i == 0) {
        return false;
    }
}

We check for any divisor from 2 up to number-1. If the number is divisible by any of them, it is not prime.

return true;

If the loop completes and no divisor is found, it means the number is prime.


โš™๏ธ Sample Output

Google Advertisement

Input:

Enter a number: 7

Output:

7 is a Prime Number.

๐Ÿ“Œ Bonus Tip: Optimized Version

You can also optimize the loop by checking up to √num (square root of number). This reduces execution time for large numbers.

for (int i = 2; i <= Math.sqrt(num); i++)

โœ… Conclusion

Checking whether a number is prime in Java is a great beginner-level programming task. It helps improve understanding of:

  • Loops

  • Conditionals

  • Functions

  • Basic math logic

We hope this explanation helped you learn how to write and understand a prime number checker in Java.

Want to engage with this content?

Like, comment, or share this article on our main website for the full experience!

Go to Main Website for Full Features

Rahul Kumar

Software Engineer & Tech Editor

Rahul is a software engineer and editor at Galaxy Founder, passionate about technology, startups, and digital innovation. With a keen eye for emerging trends and a love for clean, efficient code, Rahul shares insights and resources to help others navigate the evolving tech landscape.

More by this author โ†’

Published by ยท Editorial Policy

Galaxy Founder | Latest News, Job Updates & In-Depth Product Reviews โ€” Galaxy Founder brings you the latest news, real-time job postings, and honest product reviews to keep you informed, updated, and ahead. Discover trusted content across trending topics only on Galaxy Founder.

๐Ÿ‘‰ Read Full Article on Website