Prime Numbers in Java: Simple Logic and Code

Checking whether a number is prime is one of the most common beginner exercises in Java, and for good reason — it's a great way to practice loops, conditionals, and basic optimization thinking all at once.

The Core Logic

A number is prime if it's greater than 1 and divisible only by 1 and itself. The simplest approach checks divisibility from 2 up to the number itself, but a smarter approach only checks up to the square root of the number, since any larger factor would have a corresponding smaller one already checked.

  • Loop from 2 to the square root of the number instead of the full range
  • Immediately return false the moment any divisor is found
  • Handle edge cases: numbers less than 2 are never prime

Why Beginners Practice This

This exercise reinforces how loop boundaries affect performance — a small tweak (checking only up to the square root) can make the same logic run significantly faster on large numbers.

Once you're comfortable with the prime number check, try extending it to print all primes in a range — it's a natural next step that builds on the same logic.

Master Java with Uncodemy

Hands-on training, live projects, and placement support in our Java Programming Course.

Explore the Course

The Prime Check in Java

This version applies all the ideas above: it rejects numbers below 2, handles 2 separately, skips even numbers and stops at the square root.

public class PrimeCheck {

    public static boolean isPrime(int n) {
        if (n < 2) return false;          // 0, 1 and negatives
        if (n == 2) return true;          // the only even prime
        if (n % 2 == 0) return false;     // other even numbers

        for (long i = 3; i * i <= n; i += 2) {
            if (n % i == 0) return false; // found a divisor
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(isPrime(29)); // true
        System.out.println(isPrime(91)); // false (7 x 13)
    }
}

The condition i * i <= n does the same job as comparing with Math.sqrt(n) but avoids floating-point rounding. Using long for i prevents the multiplication from overflowing when n is close to the largest int value.

Tracing Two Numbers by Hand

Walking through the loop is the best way to trust it, and interviewers often ask you to do exactly this.

nChecks madeResult
29Odd. i = 3: remainder 2. i = 5: remainder 4. i = 7: 49 is greater than 29, so the loop stops.Prime
91Odd. i = 3: remainder 1. i = 5: remainder 1. i = 7: remainder 0.Not prime

For 29, only two divisions were needed instead of twenty-seven, which shows why the square-root limit matters. For 91, the loop exits as soon as it hits 7, so composite numbers are often rejected even faster. Try tracing 2, 9 and 25 yourself as well; they test the special case, a square of 3 and a square of 5, which are exactly where off-by-one mistakes in the loop condition show up.

Printing All Primes in a Range

You could call isPrime() for every number, but for a long range the Sieve of Eratosthenes is much faster. It crosses out multiples of each prime, and whatever remains uncrossed is prime.

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

public static List<Integer> primesUpTo(int limit) {
    boolean[] composite = new boolean[limit + 1];
    List<Integer> primes = new ArrayList<>();

    for (int i = 2; i <= limit; i++) {
        if (!composite[i]) {
            primes.add(i);
            for (long j = (long) i * i; j <= limit; j += i) {
                composite[(int) j] = true;
            }
        }
    }
    return primes;
}

// primesUpTo(30) -> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

Crossing out starts at i * i because smaller multiples were already crossed out by smaller primes. The trial-division check takes time roughly proportional to the square root of n, while the sieve finds every prime up to a limit in close to linear time, at the cost of an array as large as the limit.

Common Mistakes in Prime Programs

  • Treating 1 as prime, or forgetting that negative numbers and 0 are not prime.
  • Looping up to n or n / 2, which gives the right answer but wastes time.
  • Printing "prime" inside the loop before all divisors have been checked.
  • Using a flag variable but forgetting to break once a divisor is found.
  • Calling Math.sqrt(n) in the loop condition on every pass instead of once.

For very large numbers, such as those used in cryptography, Java's BigInteger.isProbablePrime() uses probabilistic tests that are far quicker than trial division.