Summarise With AI
Back

Prime Number Program in Java: Explained with Examples

15 Dec 2025
8 min read

What This Blog Covers

  • Explains prime number program in Java from fundamentals to advanced algorithms, without assuming prior knowledge.
  • Shows how and why prime-checking logic works, not just copy-paste code.
  • The blog discusses basic, optimized and advanced methods to include √n, 6k ± 1, Sieve of Eratosthenes, and Miller–Rabin. 
  • Demonstrates prime number generation in Java for ranges and first N primes using clean, reusable methods.
  • Connects prime numbers to real-world applications such as cryptography, hashing, and systems that are ​‍​‌‍​‍‌​‍​‌‍​‍‌performance-critical.

Introduction

One of the most fundamental concepts in mathematics and computer technology is prime numbers. They frequently appear in programming exams, coding interviews, competitive programming, and even real-world systems like cryptography. Despite their simplicity, many learners struggle to write correct and optimized prime number programs in Java.

This blog explains a prime number program in Java from the ground up, starting with basic logic and gradually moving toward optimized approaches. You’ll learn how prime number programs work, why certain checks are required, and how to write clean, efficient Java code for different scenarios.

What is a Prime Number?

Any natural number larger than one with precisely two different positive divisors is called a prime number:

  • 1
  • The number itself

Prime​‍​‌‍​‍‌​‍​‌‍​‍‌ numbers are those that have examples like 2, 3, 5, 7, 11, 13, etc.

Numbers such as 1, 4, 6, 8, 9, 10 are not prime since they either have more than two divisors or are not defined in that way.

Basic Prime Number Program in Java Checking Methods

The simplest way to check whether a number is prime is by testing whether it is divisible by any number other than 1 and itself.

Method 1: Basic Division Check

This method checks divisibility from 2 to n − 1.

Logic

  • If any number divides n completely, n is not prime.
  • If such a number does not exist, n is prime.

Java Example

public class PrimeBasic {
    public static void main(String[] args) {
        int num = 17;
        boolean isPrime = true;

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

        System.out.println(isPrime ? "Prime" : "Not Prime");
    }
}

Explanation

  • In this prime no code in Java, the loop works through all possible divisors to check which one divides the number. 
  • Once a divisor is found, the break command quits the verification of the remaining divisors. 
  • Such a method is quite simple, but it cannot be used for large numbers due to its ​‍​‌‍​‍‌​‍​‌‍​‍‌inefficiency.

Algorithm and Pseudocode Explanation

It​‍​‌‍​‍‌​‍​‌‍​‍‌ is very important to understand the algorithm and the logic that is working underneath before changing the code. Here is a detailed explanation of how the prime number program in Java works, step by step.

Algorithm Steps

  1. Input: Read an integer n.
  2. Edge Case: If n is less than or equal to 1, it is not a prime number.
  3. Loop:
    Loop i from 2 up to n - 1 (or up to √n for efficiency).
    • In each iteration, check if n % i == 0 (i.e., if n is divisible by i).
    • If such an i is found, n is not a prime number.
  4. If no divisors are found:
    If the loop completes without finding a divisor, n is prime.

Pseudocode for Prime Number Program in Java

START
Read n

IF n <= 1
    Print "Not Prime"
    EXIT

FOR i = 2 to n - 1
    IF n % i == 0
        Print "Not Prime"
        EXIT

Print "Prime"
END

Complexity Analysis

Understanding performance is crucial for interviews and large inputs.

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

The algorithm checks almost every number less than n, making it slow for large values.

Optimized Prime Number Algorithms

Basic methods of checking for prime no in Java are acceptable when dealing with small numbers; however, they turn out to be quite inefficient when the input size is large. Optimized prime number algorithms help to lessen the number of computations that are not necessary by using mathematical observations and more clever iteration techniques. The use of these optimizations is vital to programming competitions, technical interviews, and situations in the real world where performance is ​‍​‌‍​‍‌​‍​‌‍​‍‌important.

1. Optimization by Checking Up to √n

A number does not need to be checked against all integers up to n. The number n must have a matching factor less than the square root if its factor is bigger than the square root.

Why This Works

  • If n = a × b, then at least one of a or b must be ≤ √n
  • Checking beyond √n is redundant

Java Example

static boolean isPrime(int n) {
    if (n <= 1)
        return false;

    for (int i = 2; i * i <= n; i++) {
        if (n % i == 0) {
            return false; // optimization by break condition
        }
    }

    return true;
}

Efficiency

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

This is the most commonly expected solution in interviews.

2. Skipping Even Iterations

After checking divisibility by 2, there is no need to check other even numbers.

Optimization Idea

  • Check 2 separately: Since 2 is the only even prime number, handle it as a special case before running the loop.
  • Loop only through odd numbers: Once you have removed the even numbers, work only with odd numbers because an even number greater than 2 cannot be prime. This eliminates that part of the code from doing unnecessary checks and thus performance ​‍​‌‍​‍‌​‍​‌‍​‍‌increases.

Java Example

static boolean isPrime(int n) {
    if (n <= 1)
        return false;

    if (n == 2)
        return true;

    if (n % 2 == 0)
        return false;

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

    return true;
}

Benefit

  • Cuts nearly half the iterations
  • Faster than checking up to n/2 or all numbers

3. 6k ± 1 Optimization

Any​‍​‌‍​‍‌​‍​‌‍​‍‌ prime number bigger than 3 is expressible as 6k ± 1.

Why This Works

  • Numbers like 6k, 6k + 2, 6k + 3, and 6k + 4 are divisible either by 2 or 3,
  • Only 6k - 1 and 6k + 1 can be prime

Java Example

static boolean isPrime(int num) {
    if (num <= 1)
        return false;

    if (num <= 3)
        return true;

    if (num % 2 == 0 || num % 3 == 0)
        return false;

    for (int e = 5; e * e <= num; e += 6) {
        if (num % e == 0 || num % (e + 2) == 0)
            return false;
    }

    return true;
}

Efficiency

  • Significantly reduces divisibility checks
  • Used in high-performance prime testing

4. Sieve of Eratosthenes (Prime Numbers in a Range)

When​‍​‌‍​‍‌​‍​‌‍​‍‌ trying to find prime series in Java between two bounds, a simple check of each number is very inefficient. The Sieve of Eratosthenes works by marking the multiples of the numbers rather than testing the divisibility repeatedly.

Java Example

static void sieve(int n) {
    boolean[] prime = new boolean[n + 1];
    Arrays.fill(prime, true);

    prime[0] = prime[1] = false;

    for (int i = 2; i * i <= n; i++) {
        if (prime[i]) {
            for (int t = i * i; t <= n; t += i) {
                prime[t] = false;
            }
        }
    }

    for (int i = 2; i <= n; i++) {
        if (prime[i]) {
            System.out.print(i + " ");
        }
    }
}

Efficiency

  • Time Complexity: O(n log log n)
  • Space Complexity: O(n)

This method is popularly used in competitive programming.

5. Miller–Rabin Primality Test (Advanced Optimization)

A probabilistic technique with a primary purpose in cryptography, the Miller-Rabin primality test is typically used to test very large integers.

Key Points

  • Uses randomization and modular exponentiation
  • Much faster than deterministic methods for large values
  • Commonly used in security and hashing algorithms

Use Case

  • Cryptographic key generation
  • Large integer primality checks

6. Recursive Prime Checking

Prime checking can also be implemented using a recursive technique, though it is not optimal for performance.

Java Example

static boolean isPrimeRecursive(int n, int i) {
    if (n <= 2)
        return (n == 2);

    if (n % i == 0)
        return false;

    if (i * i > n)
        return true;

    return isPrimeRecursive(n, i + 1);
}

Note

  • Educational purpose only
  • Slower due to function call overhead

7. Prime Applications and Mathematical Use Cases

Optimized prime algorithms are the core of the following:

  • Checking if a number is a sum of two prime numbers (Goldbach’s conjecture problems)
  • Hashing algorithms and cryptography
  • Efficient generation of primes within large intervals
  • Competitive programming challenges

Recap

Optimized​‍​‌‍​‍‌​‍​‌‍​‍‌ prime number algorithms minimize the number of divisibility checks that are not necessary by utilizing mathematical patterns such as the square root rule, skipping even numbers, and the 6k ± 1 technique. Sieve-based methods are mainly used for large ranges, whereas probabilistic tests such as Miller–Rabin are employed when dealing with extremely large ​‍​‌‍​‍‌​‍​‌‍​‍‌numbers.

Generating Prime Numbers in Java

While checking whether a single number is prime is fundamental, many real-world problems require generating a list of prime numbers, either within a specific range or the first N primes. This section demonstrates how to efficiently generate such lists in Java using simple loops, reusable methods, and Java collections.

1. Finding All Prime Numbers Within a Range

To generate all prime numbers between two numbers (for example, from start to end), you can use a loop in combination with a reusable isPrime method. Storing the results in an ArrayList makes it easy to work with the list of primes later.

Example:

import java.util.List;
import java.util.ArrayList;

public class PrimeRangeGenerator {

    // Checks whether a given number is prime
    private static boolean checkPrime(int number) {
        if (number <= 1) {
            return false;
        }

        for (int divisor = 2; divisor * divisor <= number; divisor++) {
            if (number % divisor == 0) {
                return false;
            }
        }
        return true;
    }

    // Returns all prime numbers between the given range
    private static List<Integer> getPrimesBetween(int from, int to) {
        List<Integer> primeList = new ArrayList<>();

        for (int value = from; value <= to; value++) {
            if (checkPrime(value)) {
                primeList.add(value);
            }
        }
        return primeList;
    }

    public static void main(String[] args) {
        int lowerBound = 10;
        int upperBound = 50;

        List<Integer> result = getPrimesBetween(lowerBound, upperBound);

        System.out.println(
            "Prime numbers between " + lowerBound + " and " + upperBound + " are:"
        );
        System.out.println(result);
    }
}

Output:

Prime numbers between 10 and 50 are:
[11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

2. Generating the First N Prime Numbers

If you need the first N prime numbers, use a counter to track how many primes have been found and increment your candidate number until you reach N.

Example:

import java.util.List;
import java.util.ArrayList;

public class FirstNPrimeGenerator {

    // Method to verify whether a number is prime
    private static boolean isPrimeNumber(int value) {
        if (value <= 1) {
            return false;
        }

        for (int divisor = 2; divisor * divisor <= value; divisor++) {
            if (value % divisor == 0) {
                return false;
            }
        }
        return true;
    }

    // Method to generate the first N prime numbers
    private static List<Integer> generateFirstPrimes(int limit) {
        List<Integer> primeNumbers = new ArrayList<>();
        int currentNumber = 2;

        while (primeNumbers.size() < limit) {
            if (isPrimeNumber(currentNumber)) {
                primeNumbers.add(currentNumber);
            }
            currentNumber++;
        }
        return primeNumbers;
    }

    public static void main(String[] args) {
        int count = 10;

        List<Integer> primes = generateFirstPrimes(count);

        System.out.println("First " + count + " prime numbers are:");
        System.out.println(primes);
    }
}

Output:

First 10 prime numbers are:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

3. Using Java Collections for Flexibility

Making​‍​‌‍​‍‌​‍​‌‍​‍‌ use of ArrayList<Integer> or other Java collections for storing and returning prime numbers will make your code less rigid and more suitable for any kind of additional processing such as filtering, summing or exporting to different ​‍​‌‍​‍‌​‍​‌‍​‍‌formats.

When to Use Each Approach:

  • Use a simple loop with isPrime for small ranges or the first N primes.
  • Use the Sieve of Eratosthenes for generating all primes up to large numbers (e.g., 10,000 or more).
  • Always use Java collections to store primes if you need to manipulate or return the list.

Summary

Generating a list of prime numbers in Java is a common requirement in coding interviews, competitive programming, and real-world applications. By mastering both simple and efficient methods, along with Java’s collections, you’ll be ready to tackle any prime number generation problem in Java.

Prime Number Programs Using Different Java Constructs

Java allows multiple ways to implement prime-checking logic depending on the problem context.

Using a Reusable Method

static boolean isPrime(int n) {
    if (n <= 1)
        return false;

    for (int f = 2; f * f <= n; f++) {
        if (n % f == 0)
            return false;
    }

    return true;
}

Why This Is Useful

  • Improves code reusability
  • Makes programs cleaner and modular
  • Commonly expected in interviews

Using Scanner for User Input

Scanner sc = new Scanner(System.in);

int num = sc.nextInt();
System.out.println(isPrime(num) ? "Prime" : "Not Prime");

Use Case

  • Exam questions
  • Console-based applications
  • User-driven inputs

Using a While Loop

int i = 2;

while (i * i <= num) {
    if (num % i == 0) {
        isPrime = false;
        break;
    }
    i++;
}

Why This Matters

  • Demonstrates understanding of control-flow
  • Helpful when the loop structure is limited
  • Frequently varied in tests and interviews

Bottom Line

Optimized prime number algorithms reduce unnecessary checks, improve performance, and scale well for larger inputs. Whether using √n optimization or the Sieve of Eratosthenes, understanding why these methods work is more important than memorizing code, especially for interviews and real-world problem-solving.

Complexity Analysis of Prime Number Generation Algorithms

The first thing to consider when talking about prime number generation is the computational complexity that the algorithms have to deal with. This is very important if the numbers are large or the number of primes is large. The time and space complexity of common approaches are analyzed in this section, as well as their efficiency being compared and performance considerations being ​‍​‌‍​‍‌​‍​‌‍​‍‌discussed.

1. Naive Approaches

The​‍​‌‍​‍‌​‍​‌‍​‍‌ very basic way of determining if a number is prime is to verify that it is not divisible by any number between 2 and n-1 (or n/2). In the case of producing a prime list, this is the way that each candidate number is checked again.

  • Time Complexity:
    For checking a single number: O(n)
    For generating all primes up to N: O(N²) in the worst case, since each check can take up to O(N) time.
  • Space Complexity:
    O(1) per check (no extra memory needed except for counters/flags).
  • Performance Problems:
    Naive methods become impractically slow for large N due to the high number of loop ​‍​‌‍​‍‌​‍​‌‍​‍‌iterations.

2. Optimized Primality Checks (Up to √n)

By only checking divisibility up to the square root of the candidate number, we significantly reduce the number of loop iterations.

  • Time Complexity:
    For a single number: O(√n)
    For generating primes up to N: O(N√N)
  • Space Complexity:
    O(1) per check.
  • Algorithm Efficiency:
    This​‍​‌‍​‍‌​‍​‌‍​‍‌ method is considerably faster than the naive method, especially for larger numbers, but it is still not the best when a large list of primes needs to be generated.

3. Sieve of Eratosthenes

The Sieve of Eratosthenes is a classic algorithm for generating all primes up to N efficiently.

  • Time Complexity:
    O(N log log N)

The sieve obtains the primes and then marks the multiples of each prime; thus, it performs far fewer operations than if each number were checked individually.

  • Space Complexity:
    O(N)

Requires a boolean array to track which numbers are prime.

  • Memory Considerations:
    If N is very large, the space needed to store the boolean array can be quite large.
  • Best Use Case:
    When all prime numbers up to a large number are required, e.g., in competitive programming or mathematical ​‍​‌‍​‍‌​‍​‌‍​‍‌applications.

4. Probabilistic Methods

For extremely large numbers (such as those used in cryptography), probabilistic algorithms like the Miller–Rabin primality test are often used.

  • Time Complexity:
    Typically O(k log³ n), where k is the number of rounds for accuracy.
  • Space Complexity:
    O(1) or very low.
  • Performance Problems:
    While these methods are extremely fast for large numbers, they provide a probabilistic guarantee rather than absolute certainty.

Summary Table

Algorithm Time Complexity Space Complexity Best Use Case
Naive Division O(n) O(1) Small numbers, learning and basic understanding
Check up to √n O(√n) O(1) Moderate values of n, single prime checks (interviews)
Sieve of Eratosthenes O(N log log N) O(N) Generating all prime numbers up to N
Probabilistic (Miller–Rabin) O(k log³ n) O(1) Very large primes, cryptography and security systems

Key Performance Considerations

  • Loop Iterations:
    Reducing the range of divisibility checks (e.g., up to √n) greatly improves efficiency.
  • Memory Usage:
    Sieve-based algorithms consume more memory; thus, one should be careful if N is extremely large.
  • Worst Case vs. Average Case:
    Both naive and optimized checking methods might have their worst-case scenarios in large numbers, while sieve and probabilistic methods still run efficiently.
  • Algorithm Selection:
    The decision on which algorithm to use should be made based on the size of the problem, the performance requirements, and the amount of available memory.

Applications and Use Cases of Prime Numbers

Prime​‍​‌‍​‍‌​‍​‌‍​‍‌ numbers in Java are no longer only the abstract notions of math; they are the essential keys that lead to countless practical applications in computer science, cryptography, data integrity, and algorithm design. Here are the main and most practical ways prime numbers can be used in ​‍​‌‍​‍‌​‍​‌‍​‍‌programming:

  • Cryptography & Encryption Systems: For instance, in RSA and other public-key cryptosystems, prime numbers are used to secure data by multiplying them in a way that is difficult to factor.
  • Public-Key Cryptosystems: By doing so, they make possible the safe exchange of keys and authentication required in banking, cloud security, and digital communication.
  • Hash Codes & Hashing Algorithms: Thanks to prime numbers, collisions are minimized, and thus, the performance of hash tables and indexing systems is upgraded.
  • Checksums & Error Detection: Used in checksums and cyclic redundancy checks (CRC) to detect data transmission mistakes.
  • Computational Mathematics & Algorithms: Applied in algorithm optimization, number theory problems, and logic, such as the sum of two prime numbers.

Bottom Line: Prime numbers are essential for security, data integrity, and efficient algorithm design in modern computing.

Testing and Debugging Tips for Prime Number Program in Java

Just​‍​‌‍​‍‌​‍​‌‍​‍‌ writing a prime no Java program is not enough. To make sure your code is accurate and dependable, you need to adhere to the best practices of testing and debugging. Here are the main methods and the tips:

  • Test edge cases: Test also 0, 1, negative numbers, and 2 in order not to have logical errors.
  • Test a range of inputs: Check small, medium, and large positive numbers for correctness of the results.
  • Verify √n optimization: Be sure that the loop condition is correct (i * i ≤ n) so that you do not miss the divisors.
  • Use proper Java data types: Use int or long; do not use floating-point types for divisibility operations.
  • Structure code clearly: Place the prime logic in a PrimeChecker method and keep the main method short.

Bottom Line: Proper testing and debugging done with great care will ensure that the code to check prime numbers is correct and efficient.

Conclusion

Prime number program in Java is not just an academic concept; it is a practical test of how well you understand loops, conditions, optimisation, and algorithmic thinking in Java. The blog has demonstrated how prime-checking transitions from naive division to more mathematically efficient methods employed by real systems. 

When you get to the point of understanding the reasons for √n, why you skip the even numbers or why you use a sieve, then writing prime number programs comes as logic-driven rather than memory-based; that is the shift that separates beginners from problem solvers who are ​‍​‌‍​‍‌​‍​‌‍​‍‌confident. 

Key Points to Remember

  1. It​‍​‌‍​‍‌​‍​‌‍​‍‌ is always unnecessary to verify whether n is divisible by any number up to n just checking up to √n is mathematically enough, and is what you are expected to do in an interview. 
  2. The logic for primes is independent of the language; after you get it, the syntax hardly matters. 
  3. Apply the Sieve of Eratosthenes if you want to generate primes within a certain range, rather than checking if a number is prime repeatedly. 
  4. Syntax changes have little to do with interviews and competition, whereas optimizations matter a lot. 
  5. Prime numbers are the ones that make real systems work; for example, cryptography, hashing, security, and data integrity are some of the areas that rely on ​‍​‌‍​‍‌​‍​‌‍​‍‌them. 

Frequently Asked Questions

1. Why is 1 not considered a prime number?

A prime number program in Java must have exactly two distinct positive divisors. The number 1 has only one divisor (itself), so it does not meet the definition of a prime number.

2. Why do we check divisibility only up to the square root of a number?

If a number has a factor greater than its square root, it must also have a smaller factor below the square root. Checking beyond √n does not provide new information and only wastes time.

3. Which prime number approach is best for Java interviews?

Divisibility checking up to √n with early termination (break condition) is the most expected and balanced approach in interviews. It demonstrates both correctness and awareness of ​‍​‌‍​‍‌​‍​‌‍​‍‌optimization.

4. When should I use the Sieve of Eratosthenes instead of a normal prime check?

Use the Sieve of Eratosthenes when you need all prime numbers within a range (for example, up to 10,000 or more). It is much faster than checking each number individually.

5. Can prime number program in Java logic be reused across different programming languages?

Yes. The logic behind prime numbers is mathematical, not language-specific. Once you understand the concept, the same approach works in Java, Python, C, or any other language.

Summarise With Ai
ChatGPT
Perplexity
Claude
Gemini
Gork
ChatGPT
Perplexity
Claude
Gemini
Gork
Chat with us
Chat with us
Talk to career expert