Java program to check whether a number is prime or not

www‮.‬theitroad.com

Here's a Java program that checks whether a number is prime or not:

import java.util.Scanner;

public class PrimeChecker {
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = scanner.nextInt();
        if (isPrime(num)) {
            System.out.println(num + " is a prime number.");
        } else {
            System.out.println(num + " is not a prime number.");
        }
    }

    public static boolean isPrime(int n) {
        if (n <= 1) {
            return false;
        }
        for (int i = 2; i <= Math.sqrt(n); i++) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }
}

Explanation:

The program prompts the user to enter a number using the Scanner class. The number is stored in the num variable.

The program then calls the isPrime function with num as its argument to check whether num is a prime number. If isPrime returns true, the program prints the message "num is a prime number." to the console. Otherwise, the program prints the message "num is not a prime number." to the console.

The isPrime function takes an integer n as its argument and returns a boolean value indicating whether n is a prime number or not. The function first checks if n is less than or equal to 1, in which case it returns false. If n is greater than 1, the function uses a for loop to check if n is divisible by any integer between 2 and the square root of n. If n is divisible by any of these integers, the function returns false. Otherwise, the function returns true.