Java Prime Number Program

Introduction

A Prime Number is a positive integer greater than 1 that has exactly two factors: 1 and itself. In other words, a prime number cannot be divided evenly by any other number.

Examples of prime numbers are:


2, 3, 5, 7, 11, 13, 17, 19...

Numbers like 4, 6, 8, 9, 10 are not prime because they have more than two factors.

Checking whether a number is prime is one of the most common Java interview programs. It helps beginners understand loops, conditional statements, and basic mathematical logic.

In this tutorial, you’ll learn different ways to check whether a number is prime in Java.

Java Program to Check Prime Number


public class PrimeNumber {
    public static void main(String[] args) {
        int number = 29;
        boolean isPrime = true;
        if (number <= 1) {
            isPrime = false;
        } else {
            for (int i = 2; i < number; i++) {
                if (number % i == 0) {
                    isPrime = false;
                    break;
                }
            }
        }
        if (isPrime) {
            System.out.println(number + " is a Prime Number");
        } else {
            System.out.println(number + " is not a Prime Number");
        }
    }
}

Output

29 is a Prime Number

How the Program Works?

Let's understand the logic step by step.

Step 1: Declare the Number


int number = 29;

This is the number that we want to check.

Step 2: Create a Boolean Variable


boolean isPrime = true;

Initially, we assume the number is prime.

Step 3: Handle Numbers Less Than or Equal to 1


if (number <= 1) {
    isPrime = false;
}

Numbers like 0, 1, and negative numbers are not prime.

Step 4: Check Divisibility


for (int i = 2; i < number; i++) {
    if (number % i == 0) {
        isPrime = false;
        break;
    }
}

The loop checks whether the number is divisible by any value between 2 and number - 1.

If it is divisible, the number is not prime.

Step 5: Display the Result


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

The program prints whether the number is prime or not.

Optimized Prime Number Program

Instead of checking all numbers from 2 to number - 1, we only need to check up to the square root of the number.


public class PrimeNumber {
    public static void main(String[] args) {
        int number = 29;
        boolean isPrime = true;
        if (number <= 1) {
            isPrime = false;
        } else {
            for (int i = 2; i <= Math.sqrt(number); i++) {
                if (number % i == 0) {
                    isPrime = false;
                    break;
                }
            }
        }
        if (isPrime)
            System.out.println(number + " is a Prime Number");
        else
            System.out.println(number + " is not a Prime Number");
    }
}

Output

29 is a Prime Number

Why is this faster?

If a number has a factor larger than its square root, it must also have a corresponding factor smaller than the square root.

For example:


36 = 6 × 6
49 = 7 × 7
100 = 10 × 10

Therefore, checking only up to √n significantly improves performance.

Java Program Using User Input


import java.util.Scanner;
public class PrimeNumber {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int number = scanner.nextInt();
        boolean isPrime = true;
        if (number <= 1) {
            isPrime = false;
        } else {
            for (int i = 2; i <= Math.sqrt(number); i++) {
                if (number % i == 0) {
                    isPrime = false;
                    break;
                }
            }
        }
        if (isPrime)
            System.out.println(number + " is a Prime Number");
        else
            System.out.println(number + " is not a Prime Number");
        scanner.close();
    }
}

Output

Enter a number: 17
17 is a Prime Number

Algorithm

  1. Read the number.
  2. If the number is less than or equal to 1, it is not prime.
  3. Otherwise, check divisibility from 2 to √number.
  4. If any divisor is found, the number is not prime.
  5. Otherwise, it is a prime number.
  6. Display the result.

Flowchart Logic


 Start
   │
Read Number
   │
Number <= 1?
   │
  Yes ──► Not Prime
   │
  No
   │
Check divisibility from 2 to √Number
   │
Divisor Found?
   │
  Yes ──► Not Prime
   │
  No
   │
Prime Number
   │
  End

Time Complexity

Simple Approach


O(n)

The loop checks every number from 2 to n - 1.

Optimized Approach


O(√n)

This is much faster for large numbers.

Space Complexity


O(1)

Only a few variables are used.

Common Mistakes

1. Considering 1 as a Prime Number

Incorrect:


if (number == 1)
    System.out.println("Prime");

Correct:


if (number <= 1)
    isPrime = false;

2. Forgetting the break Statement

Without break, the loop continues even after finding a divisor, leading to unnecessary iterations.

3. Loop Starting from 1

Incorrect:


for(int i = 1; i < number; i++)

Correct:


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

4. Checking Until number

Using:


i < number

works but is slower.

Using:


i <= Math.sqrt(number)

is more efficient.

Summary

The Java Prime Number program is one of the most fundamental programs for beginners. It demonstrates how to use loops, conditional statements, and mathematical logic to determine whether a number is prime.

For small numbers, a simple loop works well, but for better performance, checking divisibility only up to the square root of the number is the preferred approach. Understanding this optimization is useful for coding interviews and competitive programming.

Related Java Tutorials