Start Coding Now
🔢 Number Programsbeginner2 methods

Prime Number Program in Java - Multiple Methods

Learn how to check if a number is prime in Java. Multiple approaches including basic, optimized, and using Java 8 streams.

Last updated: 11 January 2026

Method 1: Basic Method

Check divisibility from 2 to n-1.

public class PrimeNumber {
    public static void main(String[] args) {
        int num = 29;
        boolean isPrime = true;
        
        if (num <= 1) {
            isPrime = false;
        } else {
            for (int i = 2; i < num; 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:
29 is a prime number

Explanation

Basic approach:

1. Numbers <= 1 are not prime

2. Check if any number from 2 to n-1 divides n

3. If any divisor found, not prime; otherwise prime

Time Complexity:O(n)
Space Complexity:O(1)

Method 2: Optimized (Square Root)

Only check up to square root of n.

public class PrimeNumber {
    public static void main(String[] args) {
        int num = 29;
        boolean isPrime = true;
        
        if (num <= 1) {
            isPrime = false;
        } else if (num <= 3) {
            isPrime = true;
        } else if (num % 2 == 0 || num % 3 == 0) {
            isPrime = false;
        } else {
            for (int i = 5; i * i <= num; i += 6) {
                if (num % i == 0 || num % (i + 2) == 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:
29 is a prime number

Explanation

Optimized approach:

1. All primes > 3 are of form 6k ± 1

2. Only check divisors up to √n

3. Skip even numbers after checking 2

Time Complexity:O(√n)
Space Complexity:O(1)

Frequently Asked Questions

What is a prime number?

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Examples: 2, 3, 5, 7, 11, 13...

Why is 1 not a prime number?

By definition, a prime number must have exactly two distinct positive divisors. The number 1 has only one divisor (itself), so it is not prime.

Try This Program

Copy this code and run it in our free online Java compiler.

Open Java Compiler