Java Program to Check if a Number is Prime

1. Introduction

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Checking if a number is prime is common in programming and mathematics. This blog post will guide you through writing a Java program that determines whether a given number is prime.

2. Program Steps

1. Import the Scanner class to read the user's input.

2. Prompt the user to enter a number.

3. Check if the number is prime using a loop.

4. Display the result.

5. Close the Scanner object to prevent resource leaks.

3. Code Program

import java.util.Scanner;

public class PrimeNumberCheck {
    public static void main(String[] args) {
        // Creating a Scanner object for reading input
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter a number:");
        int num = scanner.nextInt();

        // Closing the scanner
        scanner.close();

        // Checking if the number is prime
        boolean isPrime = true;
        if (num < 2) {
            isPrime = false;
        } else {
            for (int i = 2; i <= num / 2; i++) {
                if (num % i == 0) {
                    isPrime = false;
                    break;
                }
            }
        }

        // Displaying the result
        if (isPrime) {
            System.out.println(num + " is a prime number.");
        } else {
            System.out.println(num + " is not a prime number.");
        }
    }
}

Output:

Enter a number:
17
17 is a prime number.
Enter a number:
20
20 is not a prime number.

Explanation:

1. The program starts by importing the Scanner class to read a number input by the user.

2. It prompts the user to enter a number, which is stored in the variable num.

3. To determine if num is prime, the program initially assumes that num is a prime number by setting isPrime to true. It then checks if num is less than 2, setting isPrime to false for numbers less than 2, as they cannot be prime.

4. For numbers 2 and above, the program iterates from 2 to num / 2. If num is divisible by any number in this range (i.e., num % i == 0), it is not prime, and isPrime is set to false.

5. After the loop, the program checks the value of isPrime. If it remains true, num is prime, and the program prints that num is a prime number. Otherwise, it prints that num is not a prime number.

6. Finally, the Scanner object is closed to prevent resource leaks, following good programming practices.

Comments