Home / Programs / Java Program - Check if a Number is Prime
Programming Example

Java Program - Check if a Number is Prime

👁 220 Views
💻 Practical Program
📘 Step by Step Learning

A basic program to determine if a given number is a prime number.

Information & Algorithm

This Java program checks whether a given number (in this case, 29) is a prime number. It initializes a boolean variable isPrime to true and uses a for loop to iterate from 2 to number / 2. If the number is divisible by any value in this range (number % i == 0), it sets isPrime to false and breaks out of the loop. After the loop, it prints whether the number is prime based on the value of isPrime. If isPrime remains true, the number is prime; otherwise, it is not.

Given Input:


29

Expected Output:


29 is a prime number.

Program Code

public class PrimeCheck {
    public static void main(String[] args) {
        int number = 29;
        boolean isPrime = true;

        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.");
    }
}

Output

29 is a prime number.

Explanation

check if any number is prime, allowing the user to input the number


import java.util.Scanner;

public class PrimeCheck {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int number = scanner.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.");
    }
}

Explanation:

  • Importing Scanner: Imports the Scanner class to read user input.
  • Creating a Scanner Object: Scanner scanner = new Scanner(System.in); creates a Scanner object to read input from the console.
  • Reading User Input: int number = scanner.nextInt(); reads an integer input from the user.
  • Prime Check Logic: The code remains largely the same, but now it checks the user-provided number instead of a hardcoded value.
  • Edge Case Handling: Added a condition to handle numbers less than or equal to 1, which are not prime.

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.