Java program to check prime number

Here’s a Java program to check whether a given number is prime or not:

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 num = sc.nextInt();
        boolean isPrime = true;

        if (num <= 1) {
            isPrime = false;
        } else {
            for (int i = 2; i <= num / 2; 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");
        }
    }
}

In this program, we first import the Scanner class from the java.util package to read input from the user.

We then prompt the user to enter a number using the System.out.print() function and read the input using the nextInt() function of the Scanner class.

Next, we declare a boolean variable isPrime and initialize it to true. We then check if the entered number is less than or equal to 1. If it is, we set isPrime to false. Otherwise, we use a for loop to check if the entered number is divisible by any number between 2 and num/2. If it is, we set isPrime to false and break out of the loop.

Finally, we use the System.out.println() function to display whether the entered number is prime or not.

When you run this program and enter a number, the output will be:

Enter a number: 13
13 is a prime number

If you enter a non-prime number like 8, the output will be:

Enter a number: 8
8 is not a prime number

This program is a basic example of how to check if a given number is prime or not using Java.