Java Program to Check Prime Number

A prime number is a number greater than 1 that has no divisors other than 1 and itself. Checking prime numbers is a common beginner programming problem in Java.

In this tutorial, we will create a Java program that checks whether a given number is prime or not using loops and conditional logic.

By the end of this guide, you will understand how loops and conditions work together in Java.

Concept Overview

A number is prime if it is not divisible by any number from 2 to n/2 (or √n for optimization).

We use a loop to check divisibility and a flag variable to track whether the number is prime.

Program

Java
import java.util.Scanner;

public class PrimeNumberCheck {
    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 <= 1) {
            isPrime = false;
        } else {
            for (int i = 2; i <= num / 2; 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");
    }
}

Output

TEXT
Enter a number: 7
7 is a Prime Number

Detailed Explanation

The program starts by importing the Scanner class to take input from the user.

A boolean variable isPrime is initialized as true.

If the number is less than or equal to 1, it is not prime.

The program uses a loop from 2 to num/2 to check if the number is divisible by any value.

If a divisor is found, isPrime is set to false and the loop breaks.

Finally, the result is displayed based on the value of isPrime.

Example Walkthrough

Let us consider an example where the user enters 7.

The program checks divisibility from 2 to 3. Since no divisor is found, 7 is prime.

The output is displayed as '7 is a Prime Number'.

Applications

Prime numbers are widely used in cryptography, security algorithms, hashing techniques, and number theory.

Advantages of This Approach

This program is simple and helps beginners understand loops and condition checking.

It demonstrates how logical decisions are made in programming.

Limitations

The program is not optimized for very large numbers.

It uses a basic loop approach instead of advanced methods like checking up to √n.

Improvements You Can Make

You can optimize the loop to run up to √n instead of n/2.

You can implement more efficient algorithms for large-scale prime checking.

You can also use recursion or mathematical optimizations.

This Java program provides a strong foundation in loops and conditional logic, which are essential for problem-solving in programming.