Hero Background

Next-Gen App & Browser Testing Cloud

Trusted by 2 Mn+ QAs & Devs to accelerate their release cycles

Next-Gen App & Browser Testing Cloud

Write a Java program for printing the prime numbers?

To print prime numbers in Java, loop through a range and test each number for primality. A number is prime if it is greater than 1 and divisible only by 1 and itself. The cleanest approach uses an isPrime() helper method that checks divisibility from 2 up to the square root of the number, printing the value whenever the helper returns true.

What Is a Prime Number?

A prime number is a natural number greater than 1 that has exactly two distinct divisors: 1 and itself. For example 2, 3, 5, 7, 11, and 13 are prime. The numbers 0 and 1 are not prime, and 2 is the only even prime number because every other even number is divisible by 2. There are 25 prime numbers between 1 and 100.

Java Program to Print Prime Numbers from 1 to 100

This version uses a reusable isPrime() helper with square-root optimization, which is both readable and efficient.

public class PrimeNumbers {

    // Helper method that returns true if 'num' is prime
    static boolean isPrime(int num) {
        if (num < 2) {
            return false;
        }
        for (int i = 2; i <= Math.sqrt(num); i++) {
            if (num % i == 0) {
                return false; // found a divisor, so not prime
            }
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println("Prime numbers from 1 to 100:");
        for (int number = 2; number <= 100; number++) {
            if (isPrime(number)) {
                System.out.print(number + " ");
            }
        }
    }
}

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

Printing Prime Numbers from 1 to N (Dynamic Range)

To make the range flexible, read an upper limit N from the user and loop up to it. This is a common variation asked in interviews and coding exercises.

import java.util.Scanner;

public class PrimeUpToN {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the upper limit N:");
        int n = sc.nextInt();

        System.out.println("Prime numbers from 1 to " + n + ":");
        for (int number = 2; number <= n; number++) {
            boolean prime = true;
            for (int i = 2; i <= Math.sqrt(number); i++) {
                if (number % i == 0) {
                    prime = false;
                    break;
                }
            }
            if (prime) {
                System.out.print(number + " ");
            }
        }
        sc.close();
    }
}

Notice the break statement exits the inner loop as soon as a divisor is found, avoiding wasted iterations. For a deeper look at that pattern, see using a break statement inside a loop.

The Sieve of Eratosthenes (Fastest for Ranges)

When you need every prime up to a large N, the Sieve of Eratosthenes is far faster than testing each number individually. It marks the multiples of each prime as non-prime; whatever stays unmarked is prime.

import java.util.Arrays;

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

        for (int i = 2; i * i <= n; i++) {
            if (!isComposite[i]) {
                for (int j = i * i; j <= n; j += i) {
                    isComposite[j] = true; // mark multiples of i
                }
            }
        }

        System.out.println("Prime numbers up to " + n + ":");
        for (int i = 2; i <= n; i++) {
            if (!isComposite[i]) {
                System.out.print(i + " ");
            }
        }
    }
}

Common Mistakes and Troubleshooting

  • Treating 0 or 1 as prime: Both must be excluded. Your isPrime() should return false for any number less than 2.
  • Looping to n instead of sqrt(n): Testing divisors all the way to n works but is slow. Stop at the square root for a big speed-up.
  • Starting the divisor loop at 1: Every number is divisible by 1, so starting at 1 always reports "not prime." Start the inner loop at 2.
  • Off-by-one on the range: Using num < 100 instead of num <= 100 silently drops the last value. Confirm your boundary condition.
  • Forgetting to break early: Without a break after finding a divisor, the loop keeps running needlessly, which matters for large N.

Conclusion

Printing prime numbers in Java is a classic exercise that teaches loops, conditionals, and algorithmic thinking. Start with a clean isPrime() helper and square-root optimization for readability, make the range dynamic by reading N from input, and reach for the Sieve of Eratosthenes when performance over a large range matters. Avoid the common pitfalls around 0, 1, and loop boundaries, and your program will be both correct and efficient. To keep practicing, explore related Java exercises like checking odd or even numbers.

Frequently Asked Questions

How many prime numbers are there between 1 and 100?

There are 25 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, and 97.

Is 1 a prime number in Java?

No. A prime number must be greater than 1 and divisible only by 1 and itself. Since 1 has only a single divisor, it is not prime. Your isPrime() logic should return false for any number less than 2.

What is the most efficient way to check if a number is prime in Java?

Check divisibility only up to the square root of the number instead of up to n. If no divisor is found by then, the number is prime. For printing all primes up to a large N, the Sieve of Eratosthenes is even faster.

Why check divisibility only up to the square root?

If a number n has a factor larger than its square root, it must also have a matching factor smaller than the square root. So testing divisors up to sqrt(n) is enough to detect any divisor, which greatly reduces the number of iterations needed.

What is the Sieve of Eratosthenes?

It is an ancient algorithm that finds all primes up to N by repeatedly marking the multiples of each prime as non-prime. The numbers that remain unmarked are the primes. It is very efficient for generating all primes within a range.

How do you print prime numbers from 1 to N in Java?

Loop from 2 to N and, for each value, call an isPrime() helper that tests divisibility up to the square root. Print the number whenever isPrime() returns true. Replace the fixed 100 with a variable N read from input to make it dynamic.

Related Questions

Test Your Website on 3000+ Browsers

Get 100 minutes of automation test minutes FREE!!

Test Now...

KaneAI - Testing Assistant

World’s first AI-Native E2E testing agent.

...

TestMu AI forEnterprise

Get access to solutions built on Enterprise
grade security, privacy, & compliance

  • Advanced access controls
  • Advanced data retention rules
  • Advanced Local Testing
  • Premium Support options
  • Early access to beta features
  • Private Slack Channel
  • Unlimited Manual Accessibility DevTools Tests