Java Program to Check Prime Number

In this Java program, we will learn how to check whether a given number is a prime number using both the traditional Java approach and Java 8 features.

What is a Prime Number?

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

Examples of prime numbers are:

2, 3, 5, 7, 11, 13, 17, 19

For example, 7 is a prime number because it can only be divided evenly by 1 and 7.

1. Traditional Java Program

import java.util.Scanner;

public class PrimeNumber {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int number = sc.nextInt();
        boolean isPrime = true;
        if (number <= 1) {
            isPrime = false;
        } else {
            for (int i = 2; i <= number / 2; i++) {
                if (number % i == 0) {
                    isPrime = false;
                    break;
                }
            }
        }
        if (isPrime) {
            System.out.println(number + " is a Prime Number");
        } else {
            System.out.println(number + " is not a Prime Number");
        }
        sc.close();
    }
}

Output

Enter a number: 17
17 is a Prime Number

Explanation

The program first takes a number from the user.

A number less than or equal to 1 is not a prime number:

if (number <= 1) {
    isPrime = false;
}

For numbers greater than 1, the for loop checks whether the number is divisible by any number between 2 and number / 2.

if (number % i == 0)

If the remainder is 0, the number has another factor and therefore is not prime.


2. Java 8 Program to Check Prime Number

Java 8 introduced the Stream API, which can be used to check whether a number is divisible by any value in a range.

import java.util.Scanner;
import java.util.stream.IntStream;

public class PrimeNumberJava8 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int number = sc.nextInt();
        boolean isPrime = number > 1 &&
                IntStream.rangeClosed(2, number / 2)
                         .noneMatch(i -> number % i == 0);
        if (isPrime) {
            System.out.println(number + " is a Prime Number");
        } else {
            System.out.println(number + " is not a Prime Number");
        }
        sc.close();
    }
}

Output

Enter a number: 13
13 is a Prime Number

Explanation of Java 8 Program

The Java 8 version uses IntStream.rangeClosed() to generate numbers from 2 to number / 2.

IntStream.rangeClosed(2, number / 2)

The noneMatch() method checks whether none of the numbers divide the given number evenly:

.noneMatch(i -> number % i == 0)

Here, i -> is a lambda expression, which is one of the important features introduced in Java 8.

If no divisor is found, noneMatch() returns true, meaning the number is prime.

Difference Between Traditional Java and Java 8

FeatureTraditional JavaJava 8
Approachfor loopStream API
Lambda expressionNoYes
Stream APINoYes
% operatorYesYes
Beginner friendlyVery easyModerate
Java VersionAll common versionsJava 8+

Which Approach Should You Use?

For beginners, the traditional for loop approach is recommended because it is easier to understand and debug.

The Java 8 version is useful when learning the Stream API, lambda expressions, and functional programming.

Conclusion

Checking whether a number is prime is a common Java programming problem and interview question. The traditional approach uses a simple loop, while the Java 8 approach demonstrates how IntStream and noneMatch() can be used to solve the same problem.

Backend developer working with Java, Spring Boot, Microservices, NoSQL, and AWS. I love sharing knowledge, practical tips, and clean code practices to help others build scalable applications.

Leave a Reply

Your email address will not be published. Required fields are marked *