Java Tutorial
🔍
Java ProgramsControl FlowCheck Prime Number

Check Prime Number in Java

intermediate·  Control Flow  ·  Math

Problem

A prime number is a number greater than 1 that has exactly two factors: 1 and itself.

Given an integer, determine whether it is a prime number.

Input
29
Output
29 is prime: true

Java Program

Java
public class PrimeCheck { public static void main(String[] args) { int n = 29; boolean isPrime = n > 1; // numbers 1 and below are never prime // Only check divisors up to sqrt(n) — any factor beyond that has a matching smaller one for (int i = 2; i * i <= n; i++) { if (n % i == 0) { isPrime = false; break; // found a divisor, no need to keep checking } } System.out.println(n + " is prime: " + isPrime); } }

Output

29 is prime: true

Core Logic

You only need to test divisors up to the square root of the number — anything larger would already have a smaller matching factor.

How It Works
  1. 1isPrime starts as n > 1, since numbers ≤ 1 are never prime.
  2. 2The loop runs i from 2 upward, but only while i * i <= n — an integer-only stand-in for checking up to √n.
  3. 3At each i, n % i == 0 checks whether i divides n evenly.
  4. 4If a divisor is found, isPrime is set to false and break exits the loop immediately.
  5. 5If the loop finishes with no divisor found, n is confirmed prime.
For n = 29, the loop checks i = 2 through 5 (since 6 * 6 = 36 > 29), finds no divisor, and reports 29 as prime.
💡

Key Point: Using i * i <= n instead of Math.sqrt(n) avoids floating-point comparison and keeps the bound check a cheap integer multiply.

Key Concepts

modulo operatorloop with breaksquare-root bound

Approach 2: BigInteger.isProbablePrime()

Java
import java.math.BigInteger; public class PrimeCheckBigInteger { public static void main(String[] args) { int n = 29; // isProbablePrime() runs a Miller-Rabin test with a certainty of 100 boolean isPrime = BigInteger.valueOf(n).isProbablePrime(100); System.out.println(n + " is prime: " + isPrime); } }

Output

29 is prime: true

Core Logic

Java's BigInteger class already knows how to test primality — no need to write the divisor loop yourself.

How It Works
  1. 1BigInteger.valueOf(n) wraps the int into a BigInteger.
  2. 2.isProbablePrime(100) runs a probabilistic primality test (Miller–Rabin) with a certainty parameter of 100.
  3. 3The certainty parameter controls the probability of a false positive — higher values make a wrong answer astronomically unlikely.
BigInteger.valueOf(29).isProbablePrime(100) returns true.
💡

Key Point: 'Probable' isn't a red flag here — with a certainty of 100, the chance of a composite number being misreported as prime is far smaller than the chance of a hardware error, and this scales to numbers far too large for a trial-division loop to check quickly.

Key Concepts

BigIntegerisProbablePrime()Miller–Rabin

Related Programs