Google News
logo
Java Program to Check Whether Prime Number or Not.
Prime number is a number that is greater than 1 and divided by 1 or itself only. In other words, prime numbers can't be divided by other numbers than itself or 1.

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

In the following example Java program to check whether a number is Prime or Not :
Program :
import java.util.Scanner;

public class PrimeNumber {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a positive integer: ");
        int num = input.nextInt();

        boolean isPrime = true;
        if (num == 1) {
            isPrime = false;
        } else {
            for (int i = 2; i <= Math.sqrt(num); i++) {
                if (num % i == 0) {
                    isPrime = false;
                    break;
                }
            }
        }

        if (isPrime) {
            System.out.println(num + " is a prime number.");
        } else {
            System.out.println(num + " is not a prime number.");
        }
    }
}
Output :
Enter a positive integer: 5
5 is a prime number.
Enter a positive integer: 9
9 is not a prime number.
In this program, we first ask the user to input a positive integer using the Scanner class. We then initialize a boolean variable isPrime to true.

We check if the input number is equal to 1, in which case it is not a prime number, and set isPrime to false. Otherwise, we use a for loop to check whether the number is divisible by any integer between 2 and the square root of the number. If it is, we set isPrime to false and exit the loop using break.

Finally, we use System.out.println() to print a message indicating whether the number is prime or not to the console.