Prime Number Program in Java

Last Updated : 31 Jan 2026

A prime number is a number that is greater than 1 and divided by 1 or itself. In other words, prime numbers cannot be divided by other than itself or 1.

For example, 2, 3, 5, 7, 11, 13, 17... are the prime numbers.

Note: 0 and 1 are not prime numbers. The number 2 is the only even prime number because all the other even numbers can be divided by 2.

Algorithm

Prime Number Java Program

In this Java program, we will take a number variable and check whether the number is prime or not.

Example

Compile and Run

Output:

3 is a prime number

Prime Number Program Using User-Defined Method

In the following program, we have defined a method to check if the number is prime or not.

Example

Compile and Run

Output:

1 is not a prime number
3 is a prime number
17 is a prime number
20 is not a prime number

Prime Number Program in Java (Optimized Approach)

The following approach is a bit different from the above one. In the following program, we have implemented the logic efficiently using Math.sqrt(n) to reduce unnecessary iterations. It is an optimized approach.

Example

Compile and Run

Output:

67 is a prime number

Find Prime Numbers Between Two Numbers

We can also find prime numbers between two specified numbers.

Output:

prime numbers between 2 and 10 are:
2
3
5
7

Next TopicJava Programs