Explore Courses
  • Home
  • Blog
  • Prime Number Program in Java: How to Print and Check Prime Numbers?

Prime Number Program in Java: How to Print and Check Prime Numbers?

By Rohan Vats

Updated on May 23, 2025 | 33 min read | 46.29K+ views

Share:

Did you know that 90% of the Fortune 500 companies are using Java as their go-to choice for software development in 2025? Implementing a prime number program in Java demonstrates Java’s efficiency in handling complex algorithms, showcasing why it remains essential for enterprise-grade applications and computational tasks.

A prime number program in Java prints and checks prime numbers using optimized algorithms that balance efficiency and computational complexity. Techniques like the square root check, 6k ± 1 method, and wheel factorization reduce redundant divisibility tests. 

These methods leverage fundamental programming constructs such as loops, conditionals, and mathematical properties to ensure correctness and performance. Java’s strong typing and built-in libraries facilitate precise and scalable implementations for prime number computations.

In this blog, we will explore how to print and check prime numbers using different methods of Java. 

Want to sharpen your programming skills with industry-level proficiency in Java? upGrad’s Online Software Development Courses can equip you with tools and strategies to stay ahead. Enroll today!

How to Implement a Prime Number Program in Java to Print Prime Numbers from 1 to 100?

Printing prime numbers from 1 to 100 involves iterating through a numeric range while applying conditional checks for divisibility. The prime number program in Java uses nested looping and boolean flags to determine primality efficiently for this range. Understanding this approach strengthens your grasp of fundamental algorithmic concepts, including conditional probabilities and loop control in Java.

If you want to learn essential programming skills to perform industry-relevant functions in Java, the following courses can help you succeed. 

  • Looping through numbers: You iterate from 2 to 100, as 1 is not prime by definition. This outer loop represents the candidate numbers to check.
  • Inner divisibility check: For each candidate, a nested loop tests divisibility by all integers from 2 up to one less than the candidate. If divisible, the candidate is not prime.
  • Boolean flag usage: A boolean variable isPrime tracks whether a number passes the divisibility test. This flag is essential for controlling the flow without unnecessary checks.
  • Early loop termination: The break statement stops the inner loop as soon as a divisor is found, optimizing runtime by avoiding redundant calculations.
  • Prime number output: Numbers identified as prime via this method are printed immediately, demonstrating dynamic result generation in Java.

Code Example:

public class PrimeNumber {
    public static void main(String[] args) {
        for (int num = 2; num <= 100; num++) {
            boolean isPrime = true;

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

            if (isPrime) {
                System.out.println(num);
            }
        }
    }
}

Output:

2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97

Output Explanation:
The output lists all prime numbers between 1 and 100. The program verifies each number’s primality by checking divisibility conditions and prints it when confirmed prime.

Use Case:

This prime number program in Java is ideal when learning looping and conditional logic fundamentals. If you’re developing basic number theory applications, this method offers clear implementation insight. You can build on this to create more complex algorithms, such as prime factorization or cryptographic key generation.

Now, let’s explore what are some of the prominent methods in Java to check and print prime number program in Java

Coverage of AWS, Microsoft Azure and GCP services

Certification8 Months

Job-Linked Program

Bootcamp36 Weeks

Which Methods in Java Check and Print Prime Numbers?

Multiple algorithms exist in Java for checking and printing prime numbers, each balancing trade-offs between computational complexity and implementation clarity. From basic divisor counting and brute-force methods to mathematically optimized techniques like the square root check, 6k ± 1 filtering, and wheel factorization, these approaches progressively reduce unnecessary calculations. 

Selecting the appropriate method depends on input scale, performance requirements, and use case complexity, enabling tailored solutions from educational prototypes to high-performance cryptographic applications.

Let’s understand how you can use java program to print prime numbers using Brute-Force prime number program. 

1. How to Print Prime Numbers Using Brute-Force Prime Number Program in Java? 

The brute-force approach tests divisibility of a target number by all integers from 2 to n-1, verifying primality through exhaustive checks. This prime number program in Java implements nested looping and modulus operations to identify prime status, a foundational algorithm relevant across Java, JavaScript, ReactJS, and Node.js environments. While straightforward, this method’s linear time complexity limits scalability for significant inputs, it remains essential for teaching and small-scale testing.

 

  • Prime check function: The isPrime(int n) method systematically tests divisibility using a for-loop, returning false if any divisor exists, and true otherwise.
    Boundary conditions: Numbers less than or equal to 1, including zero and negatives, are excluded from primality via immediate false return, ensuring a valid input domain.
  • Divisibility testing: The loop iterates from 2 to n-1, applying the modulus operator % to determine divisibility, a critical conditional check in prime verification.
  • Immediate exit optimization: Upon detecting a divisor, the function halts further checks using a return statement, optimizing runtime by avoiding unnecessary iterations.
  • Output mechanism: The main method executes the prime check on a predefined number (17) and outputs the primality result, demonstrating program flow and boolean logic in Java.

Code Example:

public class PrimeCheckBruteForce {
    public static boolean isPrime(int n) {
        if (n <= 1) {
            return false;  // 0, 1, and negatives are not prime
        }
        for (int i = 2; i < n; i++) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        int number = 17;
        if (isPrime(number)) {
            System.out.println(number + " is prime.");
        } else {
            System.out.println(number + " is not prime.");
        }
    }
}

Output:

17 is prime.

Output Explanation:

The function evaluates the number 17 by checking divisibility from 2 to 16. Since 17 has no divisors other than one and itself, the method returns true, prompting the output "17 is prime."

Time Complexity Analysis:

Java's brute-force prime number program operates with O(n) time complexity, implying linear growth in divisibility checks proportional to the input size. This characteristic restricts its efficiency in large-scale scenarios but suits smaller inputs and educational purposes.

  • The brute-force prime number program in Java operates with O(n) time complexity, where n is the number being tested.
  • This linear time means the number of divisibility checks grows proportionally with the input size.
  • While inefficient for large inputs, this method remains practical for small ranges and learning purposes.

When to Use the Brute-Force Method?

You should apply this method when learning foundational programming concepts or running correctness tests on small numbers with minimal performance demands. Additionally, understanding this approach is beneficial before exploring optimized JavaScript, ReactJS, or Node.js algorithms.

  • Use this method when introducing fundamental programming concepts like loops and conditionals.
  • It is suitable for validating small numbers where performance isn’t critical.
  • Understanding brute-force primes aids transitioning to optimized algorithms in JavaScript, ReactJS, and Node.js environments.

Example Scenario

Suppose you’re developing a simple web application using ReactJS and want to validate user inputs as prime numbers before submission. Implementing this brute-force prime number program in Java can quickly help you prototype the backend logic. You can later translate this logic into JavaScript or Node.js for client-side or server-side validation.

If you want to gain expertise on software development processes and industry-relevant programming skills such as Java, check out upGrad’s Generative AI Mastery Certificate for Software Development. The program will help you integrate AI and optimize your development workflows for enterprise-grade applications. 

Now’ let’s understand how you can print prime numbers in Java from 1 to 100 using the square root optimization method.

2. How to Print Prime Numbers from 1 to 100 Using the Square Root Optimization Prime Number Program in Java?

The square root optimization method enhances the prime number program in Java by limiting divisibility checks to values up to the square root of the candidate number. This reduces the number of iterations significantly, improving efficiency without sacrificing accuracy. The optimization is especially beneficial when dealing with larger inputs, reflecting principles applicable in CSS performance tuning, HTML rendering, and HTTP request handling.

  • Reduced divisor checks: Tests divisibility only up to √n, minimizing iterations and improving computational efficiency.
  • Mathematical rationale: Divisors larger than √n have complementary smaller factors already checked, eliminating redundant checks.
    Boolean flag usage: isPrime tracks primality within optimized bounds, controlling early exit on divisor detection.
  • Optimized loop termination: The inner loop breaks immediately when a divisor is found, saving processing time.
  • Cross-technology relevance: The efficiency concept translates to frontend optimizations in CSS and HTML and backend request validations in HTTP.

Code Example:

public class PrimeNumber {
    public static void main(String[] args) {
        for (int num = 2; num <= 100; num++) {
            boolean isPrime = true;
            for (int i = 2; i <= Math.sqrt(num); i++) {
                if (num % i == 0) {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) {
                System.out.println(num);
            }
        }
    }
}

Output:

2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97

Output Explanation

The program prints all prime numbers between 2 and 100 by checking divisibility only up to the square root of each number. Non-primes such as 4, 6, and 9 are efficiently skipped due to early divisor detection within the optimized range.

Example Scenario

Imagine you’re building a Node.js backend service that validates prime numbers submitted by users in an educational app. Using this square root optimized prime number program in Java as a reference, you can implement a performant, scalable algorithm in JavaScript to handle validation efficiently. This approach ensures a responsive user experience even as the input size grows.

Time Complexity Analysis

The square root optimization lowers time complexity from O(n) to O(√n), significantly reducing the number of divisibility checks. This makes the prime number program in Java more efficient for larger inputs, balancing speed and simplicity. Early loop exits further decrease runtime by avoiding redundant calculations once a divisor is found.

  • The square root optimization reduces time complexity from O(n) in brute-force to O(√n), offering significant performance gains for larger n.
  • Early loop breaks further reduce the average-case runtime by stopping divisibility checks once a factor is found.
  • This complexity balance makes the method practical for inputs ranging up to hundreds of thousands and suitable for algorithmic coding challenges.

When to Use the Square Root Optimization Method?

This method suits scenarios involving moderate to large numbers where brute-force becomes impractical. It is commonly used in coding interviews and programming contests requiring efficient prime checks. Beyond algorithms, the principles help optimize related processes in web technologies like CSS selector matching and HTTP request filtering.

  • Apply this method for prime checks involving moderate to large numbers where brute-force becomes inefficient.
  • It is highly recommended in interview scenarios and programming contests demanding optimized solutions.
  • The method’s principles can be extended to performance improvements in web technologies like CSS selector efficiency and HTTP request filtering.

If you want to learn advanced SQL functions for orgaizational Java applications, check out upGrad’s Advanced SQL: Functions and Formulas. The 11-hour free program will help you learn SQL, MySQL, and more. 

Example Scenario

Imagine you’re building a Node.js backend service that validates prime numbers submitted by users in an educational app. Using this square root optimized prime number program in Java as a reference, you can implement a performant, scalable algorithm in JavaScript to handle validation efficiently. This approach ensures responsive user experience even as the input size grows.

Let’s explore how you can use Java program to print prime numbers from 1 to 100 using 6k ± 1 Prime Number Method

3. How to Print Prime Numbers from 1 to 100 Using the 6k ± 1 Prime Number Method in Java? 

The 6k ± 1 prime number method optimizes primality testing by focusing only on candidates that fit a specific mathematical pattern. This pattern filters out multiples of 2 and 3 early, reducing the search space before applying detailed checks. This prime number program in Java applies advanced looping, conditional logic, and mathematical insight, concepts relevant across languages like C++ and C# for efficient prime computation.

 

  • Mathematical pattern filtering: Only numbers of the form 6k ± 1 are tested as potential primes, eliminating obvious composites.
  • Initial seed primes: The algorithm explicitly includes 2, 3, and 5, which don’t fit the pattern but are essential base primes.
  • Efficient primality check: The isPrime() function uses the square root optimization and excludes multiples of 2 and 3 early for faster execution.
  • Loop constructs: The main loop generates candidates via 6k - 1 and 6k + 1, minimizing redundant checks and improving performance.
  • Cross-language applicability: This algorithmic pattern and optimizations can be implemented similarly in C++ and C# environments, making it versatile.

Code Example:

import java.util.ArrayList;

public class PrimeNumber6kMethod {
    public static void main(String[] args) {
        int n = 100; // Upper limit to find primes up to 100
        ArrayList<Integer> primes = new ArrayList<>();

        // Add the first three prime numbers explicitly
        if (n >= 2) primes.add(2);
        if (n >= 3) primes.add(3);
        if (n >= 5) primes.add(5);

        // Generate numbers using 6k ± 1 pattern and check for primality
        for (int k = 1; 6 * k - 1 <= n || 6 * k + 1 <= n; k++) {
            int num1 = 6 * k - 1; // 6k - 1
            int num2 = 6 * k + 1; // 6k + 1

            if (num1 <= n && isPrime(num1)) {
                primes.add(num1);
            }
            if (num2 <= n && isPrime(num2)) {
                primes.add(num2);
            }
        }

        // Print the prime numbers
        System.out.println("Prime numbers from 1 to " + n + ":");
        for (int prime : primes) {
            System.out.print(prime + " ");
        }
    }

    // Helper method to check if a number is prime
    public 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 i = 5; i * i <= num; i += 6) {
            if (num % i == 0 || num % (i + 2) == 0) return false;
        }
        return true;
    }
}

Output:

Prime numbers from 1 to 100:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

Output Explanation:

The program lists prime numbers by generating candidates using the 6k ± 1 formula and verifying primality through an optimized isPrime() function. Composite numbers outside the pattern or failing divisibility tests are effectively excluded.

Time Complexity Analysis

Java's 6k ± 1 prime number program reduces redundant checks by eliminating multiples of 2 and 3 upfront. The isPrime() helper maintains O(√n) complexity through square root divisibility testing, enhanced by early exits on factor detection.

  • Time complexity per candidate is O(√n).
  • Candidate filtering reduces the total numbers tested, improving practical runtime.
  • The method balances speed and readability, making it efficient for mid-sized inputs.

When to Use the 6k ± 1 Prime Number Method?

This method suits scenarios demanding more optimization than brute-force but less complexity than sieve algorithms. It’s well-suited for competitive programming, interview challenges, and numeric computations in languages like C++ and C#.

  • Ideal for n ranging from thousands to millions, where basic optimization helps.
  • Useful in programming contests requiring efficient prime checks.
  • Applicable when algorithmic clarity is important alongside performance.

Example Scenario

Suppose you’re developing a cryptographic module in C++ that requires frequent prime number validations. Implementing the 6k ± 1 prime number program logic from Java improves performance while maintaining accuracy. This ensures faster computations and resource efficiency, especially with larger prime ranges.

Now, let’s explore how you can use Java program to print prime numbers using the Arithmetic prime number method. 

4. How to Print Prime Numbers from 1 to 100 Using the Arithmetic Prime Number Method in Java?

Arithmetic prime number methods leverage mathematical patterns and precomputation to identify primes efficiently. Unlike brute-force checking, these methods reduce unnecessary checks, enhancing performance, especially for large input ranges. 

The Sieve of Eratosthenes is a classic arithmetic algorithm that uses boolean arrays to mark composite numbers, enabling fast prime enumeration, a concept analogous to precomputed indices in MySQL or tensor masking in PyTorch and TensorFlow for efficient computations.

  • Boolean marking: Uses a boolean array isPrime[] to represent primality status, similar to how tensors or arrays represent states in PyTorch or TensorFlow.
  • Early elimination: Numbers 0 and 1 are explicitly marked as non-prime to enforce domain constraints.
  • Iterative marking: Starts with the smallest prime (2) and marks all its multiples as non-prime, analogous to filtering non-significant data in tensor operations.
  • Efficient iteration: Subsequent primes are found by scanning for unmarked numbers, leveraging the property that a composite must have a prime factor less than or equal to its square root.
  • Precomputation benefits: Like MySQL indexing, the sieve’s precomputed prime list accelerates multiple queries or repeated primality checks.

Code Example:

import java.util.Arrays;

public class PrimeNumberArithmeticMethod {
    public static void main(String[] args) {
        int n = 100; // Upper limit
        boolean[] isPrime = new boolean[n + 1];

        // Step 1: Assume all numbers are prime initially
        Arrays.fill(isPrime, true);

        // Step 2: 0 and 1 are not prime numbers
        isPrime[0] = false;
        isPrime[1] = false;

        // Step 3: Start marking multiples of primes
        for (int p = 2; p * p <= n; p++) {
            if (isPrime[p]) { // If p is prime, mark its multiples
                for (int multiple = p * p; multiple <= n; multiple += p) {
                    isPrime[multiple] = false;
                }
            }
        }

        // Step 4: Print all prime numbers
        System.out.println("Prime numbers from 1 to " + n + ":");
        for (int i = 2; i <= n; i++) {
            if (isPrime[i]) {
                System.out.print(i + " ");
            }
        }
    }
}

Output:

Prime numbers from 1 to 100:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

Output Explanation

The sieve program prints all prime numbers up to 100 by marking multiples of each prime as non-prime in a boolean array. This bulk elimination parallels tensor masking in deep learning frameworks, enhancing computational efficiency.

Time Complexity Analysis

Sieve of Eratosthenes runs in O(n log log n) time, outperforming trial division methods with O(n√n) complexity.

  • Precomputation allows instant primality queries, similar to indexed lookups in MySQL databases.
  • Space complexity is O(n), requiring memory proportional to the input size.
  • The method scales efficiently, making it suitable for large inputs and high-performance computing contexts like PyTorch or TensorFlow.

When to Use the Arithmetic (Sieve) Prime Number Method?

This method generates large prime sets quickly and is favored in coding competitions and applications requiring frequent primality checks.

  • Ideal when n is large, where trial division methods become computationally expensive.
  • Useful when prime lists need to be reused across multiple operations or queries, leveraging precomputation.
  • Applicable in high-performance environments, including database indexing (MySQL) and machine learning workflows (PyTorch, TensorFlow).

Example Scenario

Imagine you’re implementing a PyTorch model that requires efficient masking of prime-indexed features for selective computation. Using the Sieve of Eratosthenes prime number program from Java as a conceptual guide, you can generate prime masks efficiently. This enables optimized tensor operations and faster training times in deep learning pipelines.

Let’s understand how to print prime numbers in Java using the wheel factorization prime number method. 

5. How to Print Prime Numbers from 1 to 100 Using the Wheel Factorization Prime Number Method in Java?

Wheel factorization enhances prime detection by systematically skipping multiples of small primes like 2, 3, 5, and 7. This method extends the 6k ± 1 approach to a larger cycle (e.g., 30k ± {1,7,11,13,17,19,23,29}), significantly reducing candidate numbers before primality tests. This optimization mirrors container orchestration strategies in Docker and Kubernetes, where unnecessary workload is filtered early to optimize resource allocation and improve efficiency.

  • Advanced candidate filtering: Eliminates multiples of small primes early, minimizing divisibility checks.
  • Cycle-based iteration: Uses a prime wheel (e.g., 30k ± offsets) to generate only viable prime candidates.
  • Boolean sieve application: Marks composite numbers efficiently, similar to task scheduling in Kubernetes clusters.
  • Square root optimization: Primality tests are refined by limiting checks to √n.
  • Scalable design: Suitable for significant inputs and bulk prime generation, paralleling scalable container management principles.

Code Example:

import java.util.ArrayList;
import java.util.Arrays;

public class PrimeNumberWheelFactorization {
    public static void main(String[] args) {
        int n = 100; // Upper limit
        ArrayList<Integer> primes = new ArrayList<>();

        // Add the first few small primes explicitly
        if (n >= 2) primes.add(2);
        if (n >= 3) primes.add(3);
        if (n >= 5) primes.add(5);
        if (n >= 7) primes.add(7);

        // Initialize boolean array for prime marking
        boolean[] isPrime = new boolean[n + 1];
        Arrays.fill(isPrime, true);

        // Eliminate multiples of known primes
        for (int i = 2; i * i <= n; i++) {
            if (isPrime[i]) {
                for (int multiple = i * i; multiple <= n; multiple += i) {
                    isPrime[multiple] = false;
                }
            }
        }

        // Wheel pattern offsets (30k ± offsets)
        int[] wheel = {1, 7, 11, 13, 17, 19, 23, 29};
        for (int k = 1; 30 * k <= n; k++) {
            for (int offset : wheel) {
                int candidate = 30 * k + offset;
                if (candidate <= n && isPrime[candidate]) {
                    primes.add(candidate);
                }
            }
        }

        // Print primes
        System.out.println("Prime numbers from 1 to " + n + ":");
        for (int prime : primes) {
            System.out.print(prime + " ");
        }
    }
}

Output:

Prime numbers from 1 to 100:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

Time Complexity Analysis

Wheel Factorization reduces unnecessary prime checks by leveraging patterns that exclude multiples of small primes early. This method combines sieve techniques' O(n log log n) efficiency with O(√n) primality tests, resulting in a balanced and scalable algorithm. Its performance gains make it suitable for large input sizes without compromising accuracy.

  • The method runs in O(n²) due to nested loops iterating divisors.
  • This quadratic complexity is significantly slower than optimized methods like the square root check or sieve algorithms.
  • Practical only for small input ranges or educational demonstrations.

When to Use the Wheel Factorization Prime Number Method?

Use this method when generating prime numbers at scale, where traditional approaches become too slow. It is ideal for performance-critical environments such as cryptography and large-scale data processing. The algorithm’s filtering strategy also parallels resource optimization in containerized systems like Docker and Kubernetes, where eliminating redundant tasks improves throughput.

  • When learning the basics of prime detection without concern for performance.
  • For very small inputs or debugging algorithm correctness.
  • When algorithmic simplicity outweighs computational efficiency, e.g., initial Kubernetes job scripts or Docker container health checks.

Example Scenario:

You can apply the Wheel Factorization prime number program in Java when handling large datasets requiring fast prime detection. This method is especially useful in cryptographic applications where quick, reliable prime generation is critical. If you work with container orchestration tools like Docker or Kubernetes, the early filtering approach mirrors workload optimization, ensuring efficient and scalable computations.

Now, let’s understand how to print prime numbers from 1 to 100 in Java using the count prime number program. 

6. How to Print Numbers from 1 to 100 Using the Count Prime Number Program in Java? 

The count prime number method in Java offers a straightforward way to detect prime numbers by counting their divisors. This technique checks each number’s divisibility count, printing it as prime if exactly two divisors exist, 1 and the number itself. 

While simple, it lacks the efficiency of optimized methods like the square root or 6k ± 1 algorithms. This approach is valuable for foundational learning and parallels basic validation steps in web development and Bootstrap form handling, where clarity sometimes outweighs performance.

  • Divisor counting logic: For each number, counts how many integers divide it evenly, identifying primes by exactly two divisors.
  • Nested looping: Employs an outer loop over candidate numbers and an inner loop checking divisibility, reflecting straightforward control flows often seen in front-end scripting.
  • Clear condition: Primes are recognized only when the divisor count equals two, ensuring correctness without complex optimizations.
  • Readability focus: The method prioritizes code simplicity and readability, similar to clean Bootstrap markup in UI design.
  • Educational analogy: Serves as an introductory example before adopting more efficient algorithms, akin to starting with basic HTML forms before using advanced JavaScript validation in web projects.

Code Example:

public class PrimeNumber {
    public static void main(String[] args) {
        for (int num = 2; num <= 100; num++) {
            int count = 0;
            for (int i = 1; i <= num; i++) {
                if (num % i == 0) {
                    count++;
                }
            }
            if (count == 2) {
                System.out.println(num);
            }
        }
    }
}

Output Example:

2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97

Output Explanation

The program prints all numbers between 2 and 100 with exactly two divisors, effectively listing primes. Composite numbers have more divisors and are automatically skipped, ensuring accuracy in a simple manner.

Time Complexity Analysis

The count prime number method employs nested loops resulting in quadratic time complexity, O(n²). This leads to a rapid increase in computations as input size grows, making it inefficient for large datasets. Despite this, its simplicity offers clear insight into basic divisibility checks, contrasting with more optimized algorithms.

  • The nested loops produce O(n²) time complexity, causing quadratic growth in operations as input size increases.
  • This inefficiency makes the method unsuitable for large inputs or performance-sensitive applications.
  • Compared to O(√n) or O(n log log n) methods, the count method is significantly slower but remains instructive.

When to Use the Count Prime Number Method?

This method suits scenarios with small input sizes or educational settings where understanding divisor concepts is more important than speed. It parallels straightforward validation logic in web development and Bootstrap forms, where clarity and simplicity often take precedence over performance optimization.

  • When working with small input ranges where performance is not critical.
  • For educational purposes to demonstrate fundamental concepts of divisibility.
  • In web development prototyping or Bootstrap-based form validation scenarios prioritizing clarity over efficiency.

Example Scenario:

You might use the count prime number program in Java when teaching beginners about loops and conditionals, or during early-stage web development prototyping where simple, easy-to-follow logic is needed. This approach aligns with Bootstrap’s philosophy of clear, maintainable code, making it ideal for learning and small-scale applications.

Now, let’s take a closer look at how to find and print prime numbers in Java within a range. 

How to Find a Prime Number in Java Within a Range? 

Determining primality within a numeric range in Java involves diverse algorithmic strategies balancing computational complexity, memory usage, and implementation elegance. From straightforward iterative loops to recursive techniques, each method uses fundamental principles like divisibility and mathematical optimizations such as square root bounds to reduce redundant checks. 

As you explore these approaches, you’ll gain practical insights applicable across domains, ranging from basic programming to scalable cryptographic computations. It empowers you to choose the best method for your specific use case and performance requirements.

Let’s dive into different methods you can use to find prime numbers in Java and see how you can implement each one with simple loops or even recursion.

Method 1: How to Find a Prime Number Using For Loop?

The for-loop method is one of the most straightforward ways to check whether a number is prime within a given range. You iterate over each number in the range and check whether it is divisible by any smaller numbers. 

If it is not divisible by any number other than 1 and itself, it is prime.

Overview of the Method

This method uses a for loop to iterate through all numbers in the specified range. 

  • For each number, you check if it is divisible by any number from 2 to that number minus one. 
  • If no divisors are found, the number is considered prime.

Steps Followed

  • Loop through all numbers in the given range.
  • For each number, check divisibility from 2 to the number minus 1.
  • If the number is not divisible by any of these, it is prime.
  • Print the prime numbers.

Example Code

public class PrimeInRange {
    public static void main(String[] args) {
        int start = 10; // Start of range
        int end = 50;  // End of range

        System.out.println("Prime numbers between " + start + " and " + end + " are:");
        for (int num = start; num <= end; num++) {
            boolean isPrime = true;
            for (int i = 2; i < num; i++) {
                if (num % i == 0) {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime && num > 1) {
                System.out.println(num);
            }
        }
    }
}

Code Explanation

  • We defined the range from 10 to 50.
  • For each number in that range, we checked divisibility starting from 2 to the number minus 1.
  • If the number is divisible by any other number, it’s marked as not prime. If it passes the divisibility test, it is considered prime.

Benefits

  • Easy to understand and implement.
  • Works well for small ranges.

Drawbacks

It is inefficient for large numbers or ranges because it checks divisibility up to n−1, which becomes slow as the numbers grow larger.

Also Read: For Loop in Java

Use Case:

You can use the for-loop method when you require clear, iterative logic to check primality across a defined range, such as in educational projects. This approach provides you precise control over iteration and immediate feedback, ideal for beginner-level implementations and when predictable loop counts aid debugging. If your use case involves straightforward prime filtering in small data sets or scripting tasks, this method balances clarity with acceptable performance.

Also Read: For Loop in Java

Method 2: How to Find Prime Numbers Using a While Loop?

The while loop method works similarly to the for loop method but uses a while loop instead. This method is especially useful when you want more control over the loop conditions or don’t know the number of iterations in advance.

Overview of the Method

This approach uses a while loop to iterate through numbers in the specified range, checking each one for primality. The logic remains the same as that of the for-loop method, but here, the iteration and checks are performed using a while loop.

Steps Followed

  • Start with the given range.
  • Use a while loop to iterate through each number.
  • For each number, check divisibility from 2 up to the square root of the number.
  • If no divisors are found, the number is prime and is printed.

Example Code

public class PrimeInRangeWhile {
    public static void main(String[] args) {
        int start = 10; // Start of range
        int end = 50;  // End of range
System.out.println("Prime numbers between " + start + " and " + end + " are:");
        int num = start;
        while (num <= end) {
            boolean isPrime = true;
            int i = 2;
            while (i <= Math.sqrt(num)) {
                if (num % i == 0) {
                    isPrime = false;
                    break;
                }
                i++;
            }
            if (isPrime && num > 1) {
                System.out.println(num);
            }
            num++;
        }
    }
}

Code Explanation

  • The while loop checks each number in the given range.
  • For efficiency, use an inner while loop to check divisibility up to the square root of the current number.
  • If a number has no divisors, it's identified as a prime.

Benefits

  • Similar to the for loop but offers more flexibility with iteration.
  • More control over the conditions inside the loop.

Drawback

It can still be inefficient for larger ranges since you check divisibility for each number.

Use Case: 

Adopting the while loop method offers you greater flexibility over iteration, especially when loop boundaries or exit conditions may vary dynamically. This technique suits scenarios where input ranges are not predetermined, or you want fine-grained control over primality checks within event-driven or interactive Java applications. In performance-sensitive contexts, the while loop combined with square root optimization ensures efficient execution while maintaining readable, maintainable code.

Also Read: Java Do While Loop With Examples

Method 3: How to Find Prime Numbers Using Recursion?

Recursion is a more advanced technique for checking whether a number is prime. In recursion, a function calls itself to break down the problem into smaller, simpler subproblems. While recursion can be elegant, it might not always be the most efficient approach, especially for large ranges.

Overview of the Method

In this method, recursion checks whether a number is divisible by any number starting from 2, up to its square root. 

The base case is simple: 

  • If the number has been checked against all divisors up to the square root, the function returns true (if no divisors are found) or false (if a divisor is found). 
  • The recursive step involves checking divisibility and calling the function again for the next divisor.

While this approach offers an elegant solution, its major drawback is the overhead of recursive function calls, especially for large numbers. But for smaller ranges, it’s a clean and efficient way to demonstrate recursion.

Steps Followed

  • Base Case: If the divisor exceeds the square root of the number and no divisors have been found, return true.
  • Recursive Step: Start checking divisibility from 2, and for each divisor, call the function again to check the next divisor.
  • Termination: If any divisor is found, return false. If the base case is met without finding any divisors, return true.

Example Code

public class PrimeRecursion {
    public static void main(String[] args) {
        int number = 29;  // Example number
        if (isPrime(number, 2)) {
            System.out.println(number + " is a prime number.");
        } else {
            System.out.println(number + " is not a prime number.");
        }
    }

    public static boolean isPrime(int number, int divisor) {
        // Base case: If divisor exceeds square root of number, it is prime
        if (divisor > Math.sqrt(number)) {
            return true;
        }
        // If number is divisible by any divisor, it is not prime
        if (number % divisor == 0) {
            return false;
        }
        // Recursive call with the next divisor
        return isPrime(number, divisor + 1);
    }
}

Output:

29 is a prime number.

Why Does It Work?

  • Base Case: If the divisor exceeds the square root of the number, it returns true, meaning no factors were found, and the number is prime.
  • Recursive Step: The function checks if the number is divisible by the current divisor and then calls itself with the next divisor.

Elegance and Efficiency

Recursion's elegance lies in its simplicity:

  • It breaks the problem down into smaller checks without needing complex loops.
  • While recursive functions are clean and easy to read. They can be inefficient for larger numbers due to the overhead of multiple function calls. 

Use Case:

Recursion is well-suited for scenarios where elegance, modularity, and conceptual clarity take precedence over raw performance, such as in academic demonstrations. When you’re developing Java applications with recursive data structures or frameworks emphasizing stack-based computation, this method aligns naturally with your design. However, for large input sizes or real-time systems, be mindful of recursion depth and overhead to maintain responsiveness.

Also Read: Recursion in Data Structure: How Does it Work, Types & When Used

How to Check Very Large Prime Numbers with Java’s BigInteger Method?

Java’s BigInteger class provides a robust solution for primality testing of very large integers beyond standard data type limits. Using its built-in isProbablePrime(int certainty) method, it employs advanced probabilistic algorithms like Miller-Rabin to efficiently determine primality with configurable confidence levels. 

This approach is vital in high-performance computing and large-scale mathematical tasks, paralleling big number handling in scripting languages like BASH and PERL for system-level operations.

  • BigInteger instantiation: Create large integers from strings or byte arrays to bypass primitive type constraints.
  • Probabilistic primality test: The isProbablePrime() method uses Miller-Rabin or similar algorithms for fast primality testing with adjustable certainty.
  • Certainty parameter: Controls the accuracy of the test; higher values reduce the probability of false positives exponentially.
  • Performance: Offers rapid testing even for numbers with hundreds or thousands of digits, critical in cryptographic key generation.
  • Cross-language relevance: Comparable big number prime checks exist in scripting environments like BASH scripting and PERL, facilitating system automation and data validation.

Code Example: 

import java.math.BigInteger;

public class PrimeCheckBigInteger {
    public static void main(String[] args) {
        // Example 11-digit prime number
        BigInteger bigNum = new BigInteger("32416190071");
        if (bigNum.isProbablePrime(10)) {
            System.out.println(bigNum + " is probably prime.");
        } else {
            System.out.println(bigNum + " is not prime.");
        }
    }
}

Output:

32416190071 is probably prime.

Output Explanation:

The program creates a BigInteger instance representing a large number and invokes isProbablePrime() with certainty 10. A return value of true indicates the number is prime with high confidence, while false confirms compositeness.

Time Complexity Analysis

  • Miller-Rabin and related algorithms run in polynomial time relative to the number of digits, making primality testing feasible for very large integers.
  • The probabilistic nature provides rapid results with controllable error margins, balancing speed and accuracy.
  • This efficiency is essential in cryptographic applications requiring large prime generation and validation.

When to Use the BigInteger Method?

  • Employ this method for cryptographic key generation and security algorithms where prime size exceeds standard numeric types.
  • Ideal for mathematical research tasks involving very large numbers that cannot be handled by primitives.
  • Useful in scripting and automation contexts using BASH or PERL where large number primality checks integrate with system operations.

Example Scenario

Suppose you are developing a security module that generates RSA keys requiring large prime numbers. Leveraging Java’s BigInteger isProbablePrime() method allows you to efficiently validate prime candidates with high certainty. This ensures cryptographic strength while maintaining acceptable performance, similar to how BASH or PERL scripts handle large integers in server automation.

Now, let’s examine how you can print prime series using different Java methods. 

How Can You Print a Prime Series in Java Using Different Methods?

A prime series in Java refers to a sequence of prime numbers printed or stored using different approaches. You can generate a prime series using methods like trial division, square root optimization, the Sieve of Eratosthenes, or 6k ± 1 filtering.

Depending on your requirements, you might need to follow the steps listed below:

  1. Print all prime numbers within a given range.
  2. Print the first N prime numbers.
  3. Store prime numbers in a list or data structure for further processing.

Each of these tasks can be achieved using different prime-checking methods. 

Below are various ways to generate a prime series in Java for a specific range.

How to Print a Prime Series in Java for a Given Range [A, B]?

If you need to print all prime numbers between two given numbers, here’s what you need to do:

  • Loop through numbers from A to B.
  • Use a prime-checking function (isPrime(n)) to verify if a number is prime.
  • Print the number if it is prime.

Code Example (Prime Series in a Range)

public class PrimeSeriesInRange {
    public 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 <= Math.sqrt(n); i += 2) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        int start = 10;
        int end = 30;
        System.out.println("Prime series in Java from " + start + " to " + end + ":");
        for (int num = start; num <= end; num++) {
            if (isPrime(num)) {
                System.out.print(num + " ");
            }
        }
    }
}

Output:

Prime series in Java from 10 to 30:
11 13 17 19 23 29

How to Print the First N Prime Numbers as a Prime Series in Java?

Sometimes, you may need the first N prime numbers rather than a range-based series. 

Here’s what you need to do in this method:

  • Start from 2 (the first prime) and check numbers one by one.
  • Maintain a count of how many primes have been found.
  • Stop when N prime numbers have been printed.

Code Example (Print First N Primes)

public class PrimeSeriesFirstN {
    public 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 <= Math.sqrt(n); i += 2) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        int N = 10; // Print first 10 prime numbers
        int count = 0;
        int num = 2;
        
        System.out.println("Prime series in Java for the first " + N + " prime numbers:");
        while (count < N) {
            if (isPrime(num)) {
                System.out.print(num + " ");
                count++;
            }
            num++;
        }
    }
}

Output:

Prime series in Java for the first 10 prime numbers:
2 3 5 7 11 13 17 19 23 29

How to Store a Prime Series in Java Using a Data Structure?

If you need to store prime numbers for later use, here’s what you can do:

  • Use an ArrayList<Integer> to collect prime numbers.
  • Print them when needed.

Code Example (Storing a Prime Series in an ArrayList)

import java.util.ArrayList;

public class PrimeSeriesStorage {
    public 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 <= Math.sqrt(n); i += 2) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        int n = 50; // Generate prime series up to 50
        ArrayList<Integer> primes = new ArrayList<>();

        for (int i = 2; i <= n; i++) {
            if (isPrime(i)) {
                primes.add(i);
            }
        }

        System.out.println("Stored prime series in Java up to " + n + ": " + primes);
    }
}

Output:

Stored prime series in Java up to 50: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

Also Read: Java Program to Print Prime Numbers in a Given Range

Why are Prime Numbers Important in Programming?

Prime numbers play a pivotal role far beyond pure mathematics, underpinning critical aspects of modern computing and technology. Their unique properties enable robust security systems, efficient data structures, and reliable algorithms essential for real-world applications. Understanding how primes work and how to programmatically generate or test them empowers you to build secure, performant, and innovative solutions across diverse domains.

Here are some real-world applications of prime numbers that show why understanding primes (and programming them) is so important:

  • Cryptography and Security: Prime numbers are fundamental to public-key encryption schemes like RSA, where the difficulty of factoring large prime products ensures data confidentiality and integrity. In RSA, two large primes are multiplied to form a public key; while multiplication is straightforward, factoring the product back into its prime components is computationally infeasible.

Efficient prime number generation using prime number programs in Java is crucial because the security strength depends on selecting large, random primes. They also enable digital signatures that authenticate software and communications, safeguarding against tampering.

  • Hashing Algorithms: Utilizing primes in hashing functions and hash table sizes reduces collisions and evenly distributes data, improving retrieval speeds and minimizing computational overhead in databases and memory management. 

Prime numbers help by breaking patterns that occur with non-prime moduli, ensuring hash functions spread keys more uniformly across buckets. This uniform distribution lowers the likelihood of clustering, thus optimizing data lookup times and overall system performance.

  • Random Number Generation: Primes facilitate pseudorandom generators by creating long, non-repetitive cycles. Algorithms like the Blum Blum Shub leverage prime properties to produce cryptographically secure random sequences vital for simulations and secure communications.
  • Error Detection: Prime moduli enhance error-detecting codes such as cyclic redundancy checks (CRCs), making it harder for structured data corruption to go unnoticed and ensuring reliability in data transmission.
  • Other Domains: Beyond computing, primes appear in network routing algorithms, biological patterns, and even musical structures. In computer science, they support randomized algorithms and advanced primality testing, integral to both theory and practical programming challenges.

Example Scenario

Imagine you’re developing a secure messaging app requiring encrypted communication channels. By implementing prime-based cryptographic algorithms like RSA using efficient prime number programs in Java, you ensure that user data remains confidential and tamper-proof. This practical application highlights how foundational prime numbers are to everyday digital security.

Also read: Explore the Top 30+ DSA projects with source code in 2025

Ready to begin your Java development journey? Explore upGrad’s Core Java Basics free course to get a solid foundation in programming and start learning today.

Let’s understand why practicing prime number program in java is important for industry-level applications. 

How Should You Practice Prime Number Programming in Java?

Effective mastery of prime number programming in Java requires deliberate, hands-on experimentation across diverse algorithms and input ranges. By systematically comparing methods like brute force, square root optimization, and 6k ± 1 filtering, you gain insights into their computational complexities and practical trade-offs. 

Extending this practice through advanced techniques such as segmented sieves and hybrid approaches deepens your understanding of edge case handling, and algorithmic correctness

You may try the following ideas:

  • Compare Different Methods: Pick a range, say up to 1,00,000, and measure how fast each method checks every number in that range. Observe how brute force struggles while the square root method and 6k ± 1 do better.
  • Implement a Segmented Sieve: If you want to generate primes in extremely large ranges without huge memory usage, the segmented sieve is an advanced extension of the classic sieve.
  • Modify Examples: Change the code to handle edge cases like negative inputs or zero. Confirm that you return false for them.
  • Combine Approaches: You could sieve up to a certain threshold and then use a primality test beyond that threshold. This combination sometimes benefits larger ranges.

Practice Problem 1: Compare Different Methods

Write Java programs to generate prime numbers up to 1,000,000 using brute force, square root optimization, and the 6k ± 1 method. Measure and record the execution time for input sizes of 10,000, 100,000, and 1,000,000.
 Tips: Use System.nanoTime() or System.currentTimeMillis() to measure runtime. Observe how brute force becomes inefficient as input size grows, while optimized methods scale better. Verify correctness by comparing outputs from all methods for smaller ranges.

Practice Problem 2: Implement a Segmented Sieve

Develop a Java program that uses the segmented sieve algorithm to generate primes within large ranges, for example from 1,000,000 to 2,000,000, with minimal memory use.
 Hints: Break the range into manageable segments, apply the classic sieve to each segment using primes up to √(end of the range). This approach balances memory usage and computational efficiency. Test with varying segment sizes and verify correctness by cross-checking known primes.

Practice Problem 3: Modify Examples for Edge Cases

Take any existing prime-checking Java program and modify it to correctly handle edge cases such as zero, negative numbers, and one. Ensure the program returns false for these inputs.
 Tips: Add explicit input validation at the start of your methods. Write unit tests covering these cases to confirm the program behaves as expected under invalid inputs.

Practice Problem 4: Combine Approaches for Large Ranges

Create a hybrid Java program that uses a sieve to generate primes up to a certain threshold (e.g., 1,000,000) and then uses an optimized primality test like 6k ± 1 for numbers beyond that threshold.
 Tips: Precompute and store primes using the sieve, then efficiently test larger numbers using these primes as factors. Benchmark the combined approach against pure sieve and pure primality test methods. Verify accuracy by comparing results to known prime lists.

Use Case:

Suppose you’re preparing for a competitive programming contest focused on numerical algorithms. By implementing, testing, and benchmarking multiple prime-checking methods in Java, you refine your problem-solving skills and build a robust toolkit. This hands-on approach ensures you can select and adapt the most efficient algorithm under time constraints, ultimately improving your coding accuracy and speed.

Also read: 50 Java Projects With Source Code in 2025: From Beginner to Advanced

How Can upGrad Help You Build a Career in Programming?

A prime number program in Java prints and checks primes using methods ranging from brute force to advanced algorithms like wheel factorization and BigInteger. Choosing the right approach depends on your input size, performance needs, and application context. To optimize, test multiple algorithms, handle edge cases, and leverage built-in Java features like BigInteger for very large numbers.

If you want to upskill yourself in Java programming skills. These are some of the additional courses from upGrad that can help understand basic and advanced functions of Java for industry-level applications. 

Curious which courses can help you gain expertise in Java and other programming languages? Contact upGrad for personalized counseling and valuable insights. For more details, you can also visit your nearest upGrad offline center. 

Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.

Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.

Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.

Frequently Asked Questions (FAQs)

1. How does the square root optimization improve prime checking performance?

2. Why is the 6k ± 1 method more efficient than brute force?

3. What advantages does wheel factorization offer over 6k ± 1 filtering?

4. When should I prefer Java’s BigInteger for primality testing?

5. How can recursion be used in prime number checking?

6. What are the trade-offs of the count divisor method?

7. How does the sieve of Eratosthenes achieve prime generation efficiency?

8. Can these prime checking methods be adapted to other languages?

9. How does early loop termination optimize prime tests?

10. Why are primes important in hashing and cryptography?

11. What considerations exist for choosing a prime checking method?

References:

  1. https://www.netguru.com/blog/is-java-still-used-in-2025

Rohan Vats

408 articles published

Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

India’s #1 Tech University

Executive PG Certification in AI-Powered Full Stack Development

77%

seats filled

View Program

Top Resources

Recommended Programs

upGrad

AWS | upGrad KnowledgeHut

AWS Certified Solutions Architect - Associate Training (SAA-C03)

69 Cloud Lab Simulations

Certification

32-Hr Training by Dustin Brimberry

upGrad

Microsoft | upGrad KnowledgeHut

Microsoft Azure Data Engineering Certification

Access Digital Learning Library

Certification

45 Hrs Live Expert-Led Training

upGrad

upGrad KnowledgeHut

Professional Certificate Program in UI/UX Design & Design Thinking

#1 Course for UI/UX Designers

Bootcamp

3 Months

upGrad Abroad Logo
LinkedinFacebookInstagramTwitterYoutubeWhatsapp

Download our App

Bachelor programs

Top Destinations

Masters programs

Study Abroad Important Blogs