Write an efficient Java program to check whether a number is prime.

A number is prime if it is greater than 1 and has no divisors other than 1 and itself. The efficient check only tests divisors up to the square root of the number, skipping even numbers.

Key Points

public class PrimeCheck {

    static boolean isPrime(int n) {
        if (n <= 1) return false;
        if (n <= 3) return true;
        if (n % 2 == 0 || n % 3 == 0) return false;
        for (long i = 5; i * i <= n; i += 6) {
            if (n % i == 0 || n % (i + 2) == 0) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        int[] numbers = {1, 2, 17, 21, 97, 7919, 2147483647};
        for (int n : numbers) {
            System.out.println(n + " is prime: " + isPrime(n));
        }
    }
}

Output

1 is prime: false

2 is prime: true

17 is prime: true

21 is prime: false

97 is prime: true

7919 is prime: true

2147483647 is prime: true

Good to Know

To find all primes up to a limit (instead of testing one number), the Sieve of Eratosthenes is faster: O(n log log n) for the whole range.

Explain why √n is the limit; that reasoning matters more to interviewers than the 6k ± 1 optimisation.

Interview Tip

A concise interview answer is

I return false for numbers up to 1, handle 2, 3 and multiples of 2 or 3 directly, then test divisors of the form 6k ± 1 only while i * i <= n. That gives O(√n) time and O(1) space, and for many numbers at once I would use the Sieve of Eratosthenes.

Last updated: 11 November 2026

Previous question: Write a Java program to iterate a HashMap using a while loop and an enhanced for loop.

Next question: Write a Java program to check whether a string or number is a palindrome.

More Java Coding Questions interview questions

All Java Coding Questions questions