Summarise With AI
Back

Understand How to Print Prime Numbers from 1 to 100 in Java with Examples

11 Feb 2026
5 min read

What This Blog Covers

  • Explains the idea of prime numbers and their significance in security and programming systems.
  • Prime numbers from 1 to 100 are checked and printed using a variety of Java approaches.
  • Covers loops and modular functions in beginner-friendly ways.
  • Presents efficient techniques such as Java Streams, ArrayList, and the Sieve of Eratosthenes.
  • Teaches you how to use sophisticated optimization strategies and manage bespoke ranges.

Introduction

You may question why print prime numbers from 1 to 100 in Java is regarded as an important part for beginners. This seemingly simple issue conceals strong reasoning that strengthens your understanding of loops, conditions, and algorithmic reasoning. 

Whether you are preparing for coding interviews, strengthening your basics, or aiming to write efficient programs, mastering prime number logic is essential. In this guide, you will learn step by step how to identify prime numbers, implement multiple Java solutions, and choose the best approach based on performance and clarity.

Prime Number Concept

Before using any strategy to find prime numbers in Java or other computer languages, it is important to comprehend the idea of prime numbers. Prime numbers are a basic concept in number theory with real-world applications in fields like hashing, coding theory, and cryptography.

What is a Prime Number?

A natural number larger than one that has precisely two different positive divisors—1 and itself is called a prime number. To put it another way, you cannot multiply two lesser natural numbers (except from 1 and itself) to get a prime number.

Key Properties:

  • Divisibility: A prime number is only divisible by 1 and itself, with no other positive divisors.
  • Boundary Conditions: 0 and 1 are not considered prime numbers.
  • Even and Odd Primes: 2 is the only even prime number; all other even numbers are divisible by 2 and thus not prime.
  • Natural Numbers: The sequence of prime numbers starts from 2 (the smallest prime).

Examples of Prime Numbers:

2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, …

Examples of Non-Prime (Composite) Numbers:

4 (divisible by 2), 6 (divisible by 2 and 3), 8, 9 (divisible by 3), 10, etc.

How to Determine if a Number is Prime

To check if a number is prime, apply the following logic:

  1. Boundary Check: If the number is less than 2, it is not prime.
  2. Divisor Counting Logic: Iterate from 2 up to the square root of the number. If any divisor evenly divides the number (i.e., the remainder is zero), it is not prime.
  3. Conditionals and Loops: Use a loop and conditional statements to check each potential divisor.
  4. Boolean Array (for Sieve methods): In optimized algorithms like the Sieve of Eratosthenes, use a boolean array (e.g., isPrime[]) to track the primality status of each number in a range.

Why Primes Matter

In addition to being a mathematical curiosity, prime numbers are essential to computer science:

  • Number Theory Applications: Prime numbers provide the basis of mathematical methods and proofs.
  • Cryptography: The difficulty of factoring big integers into primes is the foundation of several encryption techniques.
  • Hash Functions: Primes are used in hashing algorithms to guarantee the uniform distribution of hash functions.
  • Algorithm Optimization: Effective primality testing and prime creation are made possible by an understanding of prime attributes.

Summary Table: Prime Number Basics

Concept Description
Definition Natural number greater than 1, divisible by 1 and itself
Smallest Prime 2
Not Prime 0, 1, negative numbers, composite numbers
Test for Primality Check divisibility up to √n
Use in Programming Loops, conditionals, boolean arrays

A solid grasp of the prime number concept is the first step toward implementing reliable and efficient prime number algorithms in Java.

Prime Number Checking Using Various Java Constructs

The theory for determining if a single integer is prime may be implemented in a variety of ways using Java. The flexibility and readability of your code can be impacted by the choice between recursion, while loops, and for loops. Here are real-world examples of each strategy.

Checking Primality with a For Loop

A for loop is the most common way to check if a number is prime. It iterates through possible divisors and uses an early exit if a divisor is found.

Example:

public static boolean isPrime(int num) {

    if (num < 2) {
        return false;
    }

    for (int i = 2; i * i <= num; i++) {

        if (num % i == 0) {
            return false;
        }
    }

    return true;
}

How it works:

  • The loop tests divisibility from 2 up to the square root of num.
  • If any divisor evenly divides num, the function returns false.
  • If no divisors are found, it returns true.

Checking Primality with a While Loop

Similar reasoning is provided by a while loop, which may be more adaptable if you need to dynamically modify the loop condition.

Example:

public static boolean isPrime(int num) {

    if (num < 2) {
        return false;
    }

    int i = 2;

    while (i * i <= num) {

        if (num % i == 0) {
            return false;
        }

        i++;
    }

    return true;
}

How it works:

  • Starts with i = 2 and checks divisibility up to sqrt(num).
  • Returns false if a divisor is found; otherwise, returns true.

Checking Primality with Recursion

Recursion can be used to check for primality by dividing the problem into smaller checks.

Example:

public static boolean isPrime(int num) {

    return isPrimeHelper(num, 2);
}

private static boolean isPrimeHelper(int num, int divisor) {

    // Base case: numbers less than 2 are not prime
    if (num < 2) {
        return false;
    }

    // If divisor squared is greater than num, it's prime
    if (divisor * divisor > num) {
        return true;
    }

    // If divisible, not prime
    if (num % divisor == 0) {
        return false;
    }

    // Recursive call
    return isPrimeHelper(num, divisor + 1);
}

How it works:

  • The helper function checks divisibility from 2 upwards.
  • If divisor * divisor > num, no divisors were found and the number is prime.
  • If a divisor is found, returns false.
  • Otherwise, recursively checks the next divisor.

Summary Table

Method Code Structure Best For
For Loop Simple, compact Most use cases
While Loop Flexible Dynamic

Tip:

Use a for loop for the majority of applications since it is efficient and clear. Recursion is the greatest way to learn or demonstrate algorithmic reasoning, although loops are useful when you need additional control.

Java Program to Print Prime Numbers from 1 to 100

This program identifies and prints all prime numbers between 1 and 100 using a basic approach. This approach offers an easy but effective method to print prime numbers from 1 to 100 in Java.

Algorithm to Print Prime Numbers from 1 to 100 in Java

  1. Start
  2. Input or define the upper limit (e.g., 100)
  3. Repeat for each number num from 2 to the limit:
  • Set a flag isPrime = true
  • Repeat for each divisor from 2 to √num:
    • If num is divisible by divisor, set isPrime = false and break
  • If isPrime is still true, print num (it is a prime number)
  1. End

Code Example:

public class PrimeNumbers {
    public static void main(String[] args) {
        int limit = 100;
        System.out.println("Prime numbers between 1 and " + limit + " are:");
        
        for (int num = 2; num <= limit; num++) {  
            boolean isPrime = true;  
            
            for (int divisor = 2; divisor * divisor <= num; divisor++) {  
                if (num % divisor == 0) {  
                    isPrime = false;  
                    break;  
                }
            }
            
            if (isPrime) {  
                System.out.print(num + " ");  
            }
        }
    }
}

Explanation:

The program checks each number from 2 to 100 and determines whether it is prime. After making the initial assumption that a number is prime, it uses values ranging from 2 to the number's square root to test for divisibility. A number is designated as non-prime if it is divisible by any of these. Only prime numbers that have been verified are printed.

Output:

Prime numbers between 1 and 100 are:  
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 and Space Complexity:

Time Complexity: O(nn​) (since each number is checked against divisors up to its square root).

Space Complexity: O(1)(since no extra space is used apart from a few variables).

Alternative Methods for Finding Prime Numbers

There are multiple ways to find prime numbers efficiently beyond the basic approach. To increase performance and versatility, the alternative approaches frequently make use of various data structures or optimizations.

1. Finding Prime Numbers Using an ArrayList

Prime numbers are dynamically stored in an ArrayList before being printed using this approach. This method offers flexibility in subsequent processing and improves the handling of prime numbers.

Code Example:

import java.util.ArrayList;

public class PrimeNumbersList {
    public static void main(String[] args) {
        int limit = 100;
        ArrayList<Integer> primes = new ArrayList<>();
        
        for (int num = 2; num <= limit; num++) {
            boolean isPrime = true;
            
            for (int divisor = 2; divisor * divisor <= num; divisor++) {
                if (num % divisor == 0) {
                    isPrime = false;
                    break;
                }
            }
            
            if (isPrime) {
                primes.add(num);
            }
        }
        
        System.out.println("Prime numbers between 1 and " + limit + ": " + primes);
    }
}
Explanation:

Using the square root approach, this program iterates over the integers 2 through 100 to determine whether each is prime. An ArrayList is used to hold numbers that are prime. The result is more organized and readable once every number has been verified since the entire list is printed at once.

Output:
Prime numbers between 1 and 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 and Space Complexity:
  • Time Complexity: O(nn​) (same as the previous method, as each number is checked up to its square root).
  • Space Complexity: O(n) (since an ArrayList is used to store all prime numbers).

2. Sieve of Eratosthenes (Optimized Approach)

A very effective way to find every prime number in a given range is to use the Sieve of Eratosthenes. It reduces needless calculations by consistently marking the multiples of each prime as non-prime rather than examining each integer separately. Using this approach, you can greatly speed up the process to print prime numbers from 1 to 100 in Java.

Code Example:

import java.util.Arrays;

public class SieveOfEratosthenes {
    public static void main(String[] args) {
        int limit = 100;
        boolean[] isPrime = new boolean[limit + 1];
        Arrays.fill(isPrime, true);

        isPrime[0] = false; // 0 is not a prime
        isPrime[1] = false; // 1 is not a prime

        for (int p = 2; p * p <= limit; p++) {
            if (isPrime[p]) {
                for (int multiple = p * p; multiple <= limit; multiple += p) {
                    isPrime[multiple] = false;
                }
            }
        }

        System.out.println("Prime numbers between 1 and " + limit + ":");
        for (int i = 2; i <= limit; i++) {
            if (isPrime[i]) {
                System.out.print(i + " ");
            }
        }
    }
}
Explanation:

This program sets up a boolean array in which each index indicates whether the corresponding number is prime. Starting from 2, it marks all multiples as non-prime. The process continues up to the square root of the limit. Any number still marked true is a prime and gets printed.

Output:
Prime numbers between 1 and 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 and Space Complexity:
  • Time Complexity: O(n log⁡ log ⁡n) (faster than previous methods).
  • Space Complexity: O(n) (due to the boolean array storing prime statuses)

3. Using a Separate Method for Prime Check

This method improves code structure by separating the prime-checking logic into a dedicated function. This makes the program more readable, reusable, and easier to maintain.

Code Example:

public class PrimeNumbersModular {
    public static void main(String[] args) {
        int maxLimit = 100;
        System.out.println("Prime numbers between 1 and " + maxLimit + " are:");
        
        for (int num = 2; num <= maxLimit; num++) {
            if (checkPrime(num)) {
                System.out.print(num + " ");
            }
        }
    }
    
    public static boolean checkPrime(int number) {
        if (number < 2) {
            return false;
        }

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

        return true;
    }
}
Explanation:

This program increases the clarity and modularity of the code by dividing the prime-checking logic into a separate checkPrime function. The main method iterates over the numbers from 2 to 100, calling checkPrime for each one. The checkPrime method checks if an integer is prime by dividing it up to its square root. A number returns true if its only divisors are 1 and itself. A number is printed if it is prime. This method facilitates debugging and increases code reuse.

Output:
Prime numbers between 1 and 100 are:
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 and Space Complexity:

Time Complexity: O(nn​) (since each number is checked against divisors up to its square root).

Space Complexity: O(1) (only a few variables are used, with no additional data structures).

4. Using Java 8 Stream API

With Java 8, the Stream API provides a functional and concise way to process collections of data. This approach allows us to filter and print prime numbers from 1 to 100 in Java efficiently using lambda expressions and streams.

Code Example:

import java.util.stream.IntStream;

public class PrimeNumbersStream {
    public static void main(String[] args) {
        int limit = 100;
        System.out.println("Prime numbers between 1 and " + limit + " are:");

        IntStream.rangeClosed(2, limit)
                .filter(PrimeNumbersStream::isPrime)
                .forEach(num -> System.out.print(num + " "));
    }

    public static boolean isPrime(int num) {
        if (num < 2) {
            return false;
        }
        
        return IntStream.rangeClosed(2, (int) Math.sqrt(num))
                .allMatch(divisor -> num % divisor != 0);
    }
}
Explanation:

This code generates integers between 2 and 100 using IntStream, then utilizes the isPrime() function to filter out non-prime results. Using allMatch(), the isPrime() function determines whether a number has any divisors up to its square root, making sure that no integer in that range divides it entirely. Lastly, forEach() is used to output all prime integers.

Output:
Prime numbers between 1 and 100 are:  
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 and Space Complexity:
  • Time Complexity: O(nn​) (similar to the basic approach, but streamlined with Java 8 features).
  • Space Complexity: O(1)(no extra storage except for function calls and stream operations).

Quick Recap

  • Use an ArrayList to store and display primes together.
  • The Sieve of Eratosthenes efficiently marks non-primes for fast results.
  • A separate method for checking primes makes the code cleaner and reusable.
  • Java 8 Streams provide a modern, concise way to filter and print primes.

Choose the method that best fits your needs for performance, clarity, or code style.

Prime Number Programs for Custom Ranges

Real-world applications frequently call for testing or listing primes within any user-specified range, even though printing prime numbers from 1 to 100 is a popular introductory exercise. Your Java application becomes more flexible and interactive when it is modified for custom ranges.

How to Print Prime Numbers Within a User-Defined Range

To print all prime numbers within a custom range, you need to:

  1. Accept user input for the lower and upper bounds of the range.
  2. Iterate through the range using a loop.
  3. Check each number’s primality using a method such as trial division or an optimized algorithm.
  4. Store or print each prime found.

Typical Components:

  • User Input: Use Scanner to read the range from the user.
  • For Loop: Iterate from the lower to the upper limit using the for loop.
  • Primality Check: To find out if an integer is prime, use a helper method such as checkPrime(int number).
  • ArrayList (Optional): Primes can be stored in an ArrayList (optional) for further processing or display. 

Example: Java Program for Custom Range

import java.util.Scanner;
import java.util.ArrayList;

public class PrimesInRange {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        // Get range from user
        System.out.print("Enter the lower bound: ");
        int lower = scanner.nextInt();

        System.out.print("Enter the upper bound: ");
        int upper = scanner.nextInt();

        ArrayList<Integer> primes = new ArrayList<>();

        // Find prime numbers in the given range
        for (int num = lower; num <= upper; num++) {

            if (checkPrime(num)) {
                primes.add(num);
            }
        }

        // Display result
        System.out.println(
            "Prime numbers between " + lower + " and " + upper + ": " + primes
        );

        scanner.close();
    }

    // Helper method to check primality
    public static boolean checkPrime(int number) {

        if (number < 2) {
            return false;
        }

        for (int i = 2; i * i <= number; i++) {

            if (number % i == 0) {
                return false;
            }
        }

        return true;
    }
}

How it works:

  • The user enters the desired numeric range.
  • The program checks each number in that range for primality using the checkPrime method.
  • All found primes are stored in an ArrayList and displayed at the end.

Practical Applications

  • Event-driven Java applications: Allow users to specify ranges dynamically.
  • Reusable code: The same logic can be applied to check for primes in any range, not just 1–100.
  • Optimized algorithms: For very large ranges, you can replace the basic primality check with more efficient algorithms (such as the Sieve of Eratosthenes for a range).

Tips for Custom Range Programs

  • Always validate user input to ensure the lower bound is less than or equal to the upper bound.
  • Consider edge cases, such as negative numbers or ranges with no primes.
  • Use more advanced methods or precompute primes for frequently asked questions or very big ranges.

Summary:

In conclusion, your Java application will be more interactive and useful for real-world activities like filtering primes inside user-specified datasets or assisting with instructional tools if it is modified to accommodate custom ranges.

Advanced Implementations and Optimizations for Prime Number Generation

When dealing with prime numbers in Java, one can use several advanced strategies to optimize the process beyond simple trial division, especially if the range is large or the application requires speed. Three of the best techniques that one can use are:

Sieve of Eratosthenes

A well-known and incredibly effective method for locating all prime numbers up to a given limit is the Sieve of Eratosthenes. It designates the multiples of each prime as non-prime rather than examining each integer separately. This is particularly useful for producing a list of primes within a predetermined range and minimizes unnecessary tests.

How it works:

  • Create a boolean array where each index represents a number’s primality.
  • Mark 0 and 1 as non-prime.
  • Starting from 2, for each number that is still marked as prime, mark all its multiples as non-prime.
  • After processing, the indices still marked as true are primes.

Efficiency:

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

When to use:

  • Best for generating all primes up to a certain number, such as 1 to 100 or larger.

6k ± 1 Method

The fact that all primes larger than three may be written in the form 6k ± 1 is the foundation of the 6k ± 1 optimization. This lowers the number of candidates you need to assess by allowing you to bypass numbers that are clearly composite (multiples of 2 and 3).

How it works:

  • For numbers greater than 3, only test numbers where num % 6 == 1 or num % 6 == 5.
  • For each candidate, check divisibility up to its square root, skipping even numbers and multiples of 3.

Efficiency:

  • Reduces the number of candidate numbers.
  • When combined with the square root check, it balances speed and simplicity.

When to use:

  • Useful for mid-sized ranges where a full sieve may be unnecessary, but you want better performance than brute-force methods.

Wheel Factorization

Wheel factorization extends the 6k ± 1 idea by using a larger cycle (the “wheel”) to skip even more composite numbers. For example, a 30-number wheel (based on the primes 2, 3, and 5) tests only numbers of the form 30k ± {1, 7, 11, 13, 17, 19, 23, 29}.

How it works:

  • Use the product of the first few prime numbers to create a wheel (2 × 3 × 5 = 30).
  • Test numbers are limited to those that match the wheel's pattern, excluding known composites.
  • Combine each candidate with a primality check (such as the square root test).

Efficiency:

  • Lowers the number of checks even more than 6k ± 1.
  • Good for applications that are performance-sensitive or have very wide ranges.

When to use:

  • Ideal for generating primes in large ranges or when integrating with sieve-based methods for even more efficiency.

Summary Table:

Method Time Complexity Recommended Use Case
Sieve of Eratosthenes O(n log log n) Bulk prime generation
6k ± 1 O(√n) per check Mid-sized, performance-focused
Wheel Factorization O(√n) per check Large ranges, maximum speed

As the range increases, these sophisticated approaches enable you to create primes far more quickly than with simple ones. For most practical applications, the Sieve of Eratosthenes or 6k ± 1 method provides an excellent balance of speed and code clarity, while wheel factorization is best suited for very large-scale prime generation.

Conclusion

To print prime numbers from 1 to 100 in Java is not just a simple code exercise; it's also a useful approach to learn how algorithms function in practical situations. Simple loops, effective checks, modular techniques, and the more sophisticated Sieve of Eratosthenes strategy are some of the methods that may be used to solve the problem. Each technique sharpens your problem-solving skills and gets you ready for challenging tasks in competitive programming, data structures, and cryptography. You gain confidence in your ability to write scalable, legible, and effective Java applications by becoming proficient in these strategies. 

Points to Remember

  • A prime number may only be divided by 1 and itself, and it is bigger than 1.
  • For the divisibility check, always go up to the square root for better performance.
  • The basic loop technique is suitable for small ranges and learning purposes.
  • If you want to generate a large number of primes fast, the Sieve of Eratosthenes is the tool.
  • Using modular and stream-based methods increases the code's readability and reusability.

Frequently Asked Questions

1. Why are prime numbers important in hashing and cryptography?

Since factoring large primes is computationally challenging, prime numbers form the basis of many cryptographic algorithms (such as RSA), which ensures the security of encrypted data. In hashing, using primes helps distribute hash values more uniformly, reducing collisions and improving lookup efficiency.

2. How do I choose the right prime-checking algorithm in Java for my needs?

The simple trial division is adequate for short ranges or educational settings. To work with bigger numbers or generate a huge number of primes, employ optimal techniques such as 6k ± 1 or the Sieve of Eratosthenes. Use probabilistic techniques from Java's BigInteger class for really big integers (such as those used in encryption).

3. What are the main trade-offs between brute-force, sieve, and probabilistic methods?

  • Brute-force: Brute-force is easy to learn but sluggish for big inputs.
  • Sieve of Eratosthenes: Fast for generating many primes, but uses more memory.
  • Probabilistic (e.g., Miller-Rabin): Extremely fast for very large numbers, but there is a small chance of false positives.

4. When should I precompute primes in Java?

Precompute primes when you need to perform many primality checks or factorization operations—this saves time in applications like competitive programming, cryptographic key generation, or data analysis.

5. How does Java’s BigInteger help with large prime numbers?

BigInteger supports arbitrarily large integers and provides the isProbablePrime() method, which uses probabilistic algorithms to efficiently check if a large number is prime, essential for cryptographic applications.

6. How can edge cases affect prime number programs?

Inputs that are not prime, such as 0 and 1, should always be handled. Use the right data types and techniques for very big numbers to prevent overflow or performance problems.

7. Can I reuse prime-checking logic in other programming languages?

Indeed. Python, C++, and JavaScript all use the same basic logic (loops, conditionals, and optimizations). The only differences are in syntax and accessible libraries.

8. How do optimized algorithms improve real-world performance?

Prime generation is sufficiently quick for use in encryption, massive data processing, and performance-critical systems thanks to optimized methods like the sieve or 6k ± 1 technique, which eliminate pointless checks.

9. In security applications, what are the dangers of employing ineffective prime-checking logic?

Ineffective algorithms can cause system lag, create security holes, or facilitate brute-force assaults. For programming that is crucial to security, always employ tried-and-true, effective techniques.

10. How are primes used in generating RSA keys?

RSA key generation involves selecting two large primes, multiplying them to form a modulus, and using their properties to create public and private keys. The security of RSA relies on the difficulty of factoring this modulus back into its original primes.

Summarise With Ai
ChatGPT
Perplexity
Claude
Gemini
Gork
ChatGPT
Perplexity
Claude
Gemini
Gork