---
description: Print Prime Number From 1 to 100 in Java - Here is a Java program to print prime numbers from 1 to 100 (1 to N) with program logic and example.
title: Java Program to Print Prime Numbers from 1 to 100
image: https://www.guru99.com/images/prime-numbers-1-to-100-in-java.png
---

 

[Skip to content](#main) 

**⚡ Smart Summary**

Program to Print Prime Number From 1 to 100 in Java scans every value in a range and reports those with exactly two divisors. This article explains the definition, the checking method, the complete program, the Sieve of Eratosthenes, and a performance comparison with verified output.

* 🔢 **Definition Rule:** A prime number is greater than 1 and divisible only by 1 and itself, which excludes 0 and 1 entirely.
* 🔁 **Range Scan:** An outer loop walks from 2 to the upper limit and delegates each value to a reusable checking method.
* ✅ **Boolean Method:** CheckPrime returns false on the first divisor found and true when the loop completes without a match.
* √ **Divisor Bound:** Testing up to half the value is correct, and stopping at the square root produces the same answer far faster.
* 🧮 **Result Set:** Exactly 25 prime numbers exist between 1 and 100, ending with 97.
* ⚡ **Sieve Method:** The Sieve of Eratosthenes marks multiples in a boolean array and runs in O(n log log n) time.
* 🧪 **Verification Practice:** Confirm that 2 is included and that 1 is excluded before trusting any implementation.

[ Read More ](javascript:void%280%29;) 

![Prime Numbers 1 to 100 in Java](https://www.guru99.com/images/prime-numbers-1-to-100-in-java.png)

## What is a Prime Number?

A **Prime Number** is a number that is only divisible by one or itself. It is a natural number greater than one that is not a product of two smaller natural numbers. For example, 11 is only divisible by one or itself. Other prime numbers are 2, 3, 5, 7, 11, 13, 17, and so on.

**Note:** 0 and 1 are not prime numbers. 2 is the only even prime number.

Between 1 and 100 there are exactly 25 prime numbers. The grid below groups them by decade, which makes the thinning pattern visible as the values grow.

| Range    | Prime Numbers              | Count |
| -------- | -------------------------- | ----- |
| 1 – 20   | 2, 3, 5, 7, 11, 13, 17, 19 | 8     |
| 21 – 40  | 23, 29, 31, 37             | 4     |
| 41 – 60  | 41, 43, 47, 53, 59         | 5     |
| 61 – 80  | 61, 67, 71, 73, 79         | 5     |
| 81 – 100 | 83, 89, 97                 | 3     |

## How to Print Prime Numbers Between 1 to 100 Program in Java

Below is the Java program to print prime numbers from 1 to 100:

**Program Logic:**

* The main method of the [prime number program in Java](https://www.guru99.com/java-program-check-prime-number.html) contains a loop to check prime numbers between 1 to 100 one by one.
* The main method calls the method `CheckPrime` to determine whether a number is a prime number in Java or not.
* We need to divide an input number, say 17, from values 2 to 17 and check the remainder. If the remainder is 0, the number is not prime.
* No number is divisible by more than half of itself. So, we need to loop through just numberToCheck/2\. If the input is 17, half is 8.5, and the loop will iterate through values 2 to 8.
* If `numberToCheck` is entirely divisible by another number, we return false, and the loop is broken.
* If `numberToCheck` is prime, we return true.
* In the main method for prime numbers 1 to 100 in Java, check whether isPrime is `TRUE` and add the value to the primeNumbersFound String.
* Lastly, print prime numbers from 1 to 100 in Java.

Separating the check into its own method is what makes the program reusable. The same CheckPrime method can be called with any upper limit simply by changing the maxCheck variable.

public class PrimeNumbers {

    public static void main(String[] args) {

        int i;
        int num = 0;
        int maxCheck = 100; // maxCheck limit till which you want to find prime numbers
        boolean isPrime = true;

        //Empty String
        String primeNumbersFound = "";

        //Start loop 2 to maxCheck
        for (i = 2; i <= maxCheck; i++) {
            isPrime = CheckPrime(i);
            if (isPrime) {
                primeNumbersFound = primeNumbersFound + i + " ";
            }
        }
        System.out.println("Prime numbers from 1 to " + maxCheck + " are:");
        // Print prime numbers from 1 to maxCheck
        System.out.println(primeNumbersFound);
    }
    public static boolean CheckPrime(int numberToCheck) {
        int remainder;
        for (int i = 2; i <= numberToCheck / 2; i++) {
            remainder = numberToCheck % i;
            //if remainder is 0 then the number is not prime and we break the loop. Else continue the loop
            if (remainder == 0) {
                return false;
            }
        }
        return true;

    }

}

### Expected Output:

The output of the prime number between 1 to 100 in the [Java program](https://www.guru99.com/java-tutorial.html) will be:

Prime numbers from 1 to 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

The value 2 passes because the inner loop condition `i <= 2 / 2` evaluates to `2 <= 1`, which is false straight away, so the method returns true without a single division.

### RELATED ARTICLES

* [15 BEST Java Books for Beginners (2026 Update) ](https://www.guru99.com/books.html "15 BEST Java Books for Beginners (2026 Update)")
* [Java Variables and Data Types ](https://www.guru99.com/java-variables.html "Java Variables and Data Types")
* [ArrayList in Java ](https://www.guru99.com/arraylist-in-java.html "ArrayList in Java")
* [Top 30 Hibernate Interview Questions and Answers (2026) ](https://www.guru99.com/hibernate-interview-questions.html "Top 30 Hibernate Interview Questions and Answers (2026)")

## Optimized Version Using the Square Root Bound

Dividing up to half of the number is correct but performs unnecessary work. Divisors always occur in pairs around the square root, so any factor above √n has a partner below it that was already tested.

public class PrimeNumbersOptimized {

    public static void main(String[] args) {
        int maxCheck = 100;
        int count = 0;
        StringBuilder result = new StringBuilder();

        for (int i = 2; i <= maxCheck; i++) {
            if (isPrime(i)) {
                result.append(i).append(" ");
                count++;
            }
        }

        System.out.println("Prime numbers from 1 to " + maxCheck + " are:");
        System.out.println(result.toString().trim());
        System.out.println("Total primes found: " + count);
    }

    public static boolean isPrime(int n) {
        if (n <= 1) return false;
        if (n == 2) return true;
        if (n % 2 == 0) return false;

        // test only odd divisors up to the square root
        for (int i = 3; i * i <= n; i += 2) {
            if (n % i == 0) return false;
        }
        return true;
    }
}

### Output:

Prime numbers from 1 to 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
Total primes found: 25

**💡 Tip:** StringBuilder replaces repeated String concatenation inside the loop. Each `+=` on a String creates a new object, which becomes measurable once the upper limit reaches several thousand.

## Print Prime Numbers Using the Sieve of Eratosthenes

When every prime in a range is needed, trial division is the wrong tool. The Sieve of Eratosthenes builds a boolean array, marks the multiples of each prime as composite, and reads off whatever remains unmarked.

The method works in three steps:

1. Create a boolean array of size n+1 and assume every index from 2 upwards is prime.
2. Starting at 2, mark every multiple of the current prime as composite.
3. Advance to the next unmarked index and repeat until the square root of n is passed.

import java.util.Arrays;

public class SieveOfEratosthenes {

    public static void main(String[] args) {
        int n = 100;
        boolean[] composite = new boolean[n + 1];

        for (int p = 2; p * p <= n; p++) {
            if (!composite[p]) {
                // start at p*p because smaller multiples are already marked
                for (int multiple = p * p; multiple <= n; multiple += p) {
                    composite[multiple] = true;
                }
            }
        }

        StringBuilder result = new StringBuilder();
        for (int i = 2; i <= n; i++) {
            if (!composite[i]) {
                result.append(i).append(" ");
            }
        }

        System.out.println("Prime numbers from 1 to " + n + " are:");
        System.out.println(result.toString().trim());
    }
}

### Output:

Prime numbers from 1 to 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

## Comparison of the Three Approaches

All three programs print the same 25 values, so the choice depends entirely on the size of the range.

| Approach              | Time Complexity | Extra Memory | Best Range                   |
| --------------------- | --------------- | ------------ | ---------------------------- |
| Trial division to n/2 | O(n²)           | O(1)         | Up to a few thousand         |
| Trial division to √n  | O(n√n)          | O(1)         | Up to a few hundred thousand |
| Sieve of Eratosthenes | O(n log log n)  | O(n)         | Millions of values           |

Check our program to find [prime numbers from any input number](https://www.guru99.com/java-program-check-prime-number.html) when a single value rather than a range must be tested. For further loop driven exercises, review the [Fibonacci series in Java](https://www.guru99.com/fibonacci-series-java.html), the [Java palindrome program](https://www.guru99.com/java-palindrome-program.html), and the [Bubble Sort algorithm in Java](https://www.guru99.com/bubble-sort-java.html). The boolean array used by the sieve is explained further in [Java arrays](https://www.guru99.com/java-arrays.html).

## FAQs

🔢 How many prime numbers are there between 1 and 100?

There are exactly 25\. The sequence begins at 2 and ends at 97, and the density decreases steadily as the values grow larger.

2️⃣ Why does the program correctly report 2 as prime?

The inner loop condition becomes 2 <= 1, which is false immediately, so no division runs and the method returns true. That single case is worth testing in every implementation.

🔧 How do I print prime numbers in a different range such as 1 to 500?

Change the maxCheck variable to 500\. To start above 1, adjust the initial value of the outer loop counter instead, and leave the checking method untouched.

⚡ Why does the sieve start marking at p multiplied by p?

Every smaller multiple of p already contains a smaller prime factor and was marked during an earlier pass. Starting at p squared avoids repeating that work.

🤖 Do AI code assistants prefer the sieve or trial division?

They typically return trial division unless the prompt mentions a large range or performance. Stating the upper limit in the request usually produces the sieve instead.

🧠 Where do prime number lists matter in machine learning systems?

Primes are chosen as hash table and feature bucket sizes because they distribute keys evenly and reduce collisions. They also seed hashing functions used in feature vectorisation.

This code is editable. Click Run to Compile + Execute   

![]()

#### Summarize this post with:

ChatGPT Perplexity Grok Google AI 

**Stay Updated on AI** **Get Weekly AI Skills, Trends, Actionable Advice.** 

##### Sign up for the newsletter

Subscribe for Free 

You have successfully subscribed.  
Please check your inbox. 

![AI-Newsletter]() Chosen by over **350,000+** professionals 

[Scroll to top ](#wrapper)Scroll to top 

× 

Toggle Menu Close 

Search for: 

Search

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://www.guru99.com/#organization","name":"Guru99","sameAs":["https://www.facebook.com/Guru99Official","https://twitter.com/guru99com"],"logo":{"@type":"ImageObject","@id":"https://www.guru99.com/#logo","url":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","contentUrl":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","caption":"Guru99","inLanguage":"en-US"}},{"@type":"WebSite","@id":"https://www.guru99.com/#website","url":"https://www.guru99.com","name":"Guru99","publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US"},{"@type":"ImageObject","@id":"https://www.guru99.com/images/prime-numbers-1-to-100-in-java.png","url":"https://www.guru99.com/images/prime-numbers-1-to-100-in-java.png","width":"700","height":"250","caption":"Prime Numbers 1 to 100 in Java","inLanguage":"en-US"},{"@type":"BreadcrumbList","@id":"https://www.guru99.com/prime-number-program-java.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":"1","item":{"@id":"https://www.guru99.com","name":"Home"}},{"@type":"ListItem","position":"2","item":{"@id":"https://www.guru99.com/java-tutorials","name":"Java Tutorials"}},{"@type":"ListItem","position":"3","item":{"@id":"https://www.guru99.com/prime-number-program-java.html","name":"Java Program to Print Prime Numbers from 1 to 100"}}]},{"@type":"WebPage","@id":"https://www.guru99.com/prime-number-program-java.html#webpage","url":"https://www.guru99.com/prime-number-program-java.html","name":"Java Program to Print Prime Numbers from 1 to 100","dateModified":"2026-07-29T16:02:49+05:30","isPartOf":{"@id":"https://www.guru99.com/#website"},"primaryImageOfPage":{"@id":"https://www.guru99.com/images/prime-numbers-1-to-100-in-java.png"},"inLanguage":"en-US","breadcrumb":{"@id":"https://www.guru99.com/prime-number-program-java.html#breadcrumb"}},{"@type":"Person","@id":"https://www.guru99.com/author/james","name":"James Hartman","description":"I am James Hartman, a seasoned professional in Oracle Certified Java Professional tutorials, specializing in crafting comprehensive guides to help you excel in your Java certification journey.","url":"https://www.guru99.com/author/james","image":{"@type":"ImageObject","@id":"https://www.guru99.com/images/james-hartman-author-v2-120x120.png","url":"https://www.guru99.com/images/james-hartman-author-v2-120x120.png","caption":"James Hartman","inLanguage":"en-US"},"worksFor":{"@id":"https://www.guru99.com/#organization"}},{"articleSection":"Java Tutorials","headline":"Java Program to Print Prime Numbers from 1 to 100","description":"Print Prime Number From 1 to 100 in Java - Here is a Java program to print prime numbers from 1 to 100 (1 to N) with program logic and example.","keywords":"java","speakable":{"@type":"SpeakableSpecification","cssSelector":[".entry-title",".summary"]},"@type":"Article","author":{"@id":"https://www.guru99.com/author/james","name":"James Hartman"},"dateModified":"2026-07-29T16:02:49+05:30","image":{"@id":"https://www.guru99.com/images/prime-numbers-1-to-100-in-java.png"},"copyrightYear":"2026","name":"Java Program to Print Prime Numbers from 1 to 100","subjectOf":[{"@type":"FAQPage","mainEntity":[{"@type":"Question","name":"How many prime numbers are there between 1 and 100?","acceptedAnswer":{"@type":"Answer","text":"There are exactly 25. The sequence begins at 2 and ends at 97, and the density decreases steadily as the values grow larger."}},{"@type":"Question","name":"Why does the program correctly report 2 as prime?","acceptedAnswer":{"@type":"Answer","text":"The inner loop condition becomes 2 &lt;= 1, which is false immediately, so no division runs and the method returns true. That single case is worth testing in every implementation."}},{"@type":"Question","name":"How do I print prime numbers in a different range such as 1 to 500?","acceptedAnswer":{"@type":"Answer","text":"Change the maxCheck variable to 500. To start above 1, adjust the initial value of the outer loop counter instead, and leave the checking method untouched."}},{"@type":"Question","name":"Why does the sieve start marking at p multiplied by p?","acceptedAnswer":{"@type":"Answer","text":"Every smaller multiple of p already contains a smaller prime factor and was marked during an earlier pass. Starting at p squared avoids repeating that work."}},{"@type":"Question","name":"Do AI code assistants prefer the sieve or trial division?","acceptedAnswer":{"@type":"Answer","text":"They typically return trial division unless the prompt mentions a large range or performance. Stating the upper limit in the request usually produces the sieve instead."}},{"@type":"Question","name":"Where do prime number lists matter in machine learning systems?","acceptedAnswer":{"@type":"Answer","text":"Primes are chosen as hash table and feature bucket sizes because they distribute keys evenly and reduce collisions. They also seed hashing functions used in feature vectorisation."}}]}],"@id":"https://www.guru99.com/prime-number-program-java.html#schema-1154708","isPartOf":{"@id":"https://www.guru99.com/prime-number-program-java.html#webpage"},"publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US","mainEntityOfPage":{"@id":"https://www.guru99.com/prime-number-program-java.html#webpage"}}]}
```
