Introduction
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. In other words, a prime number is only divisible by 1 and the number itself. For example, the numbers 2, 3, 5, 7, and 11 are prime numbers.
Objective
The objective of this program is to determine whether a given number is prime or not. This will help users understand the concept of prime numbers and provide a practical application of programming logic and algorithms.
Java Code
public class PrimeChecker {
public static void main(String[] args) {
int number = 29; // You can change this number to test other values
boolean isPrime = checkPrime(number);
if (isPrime) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}
}
public static boolean checkPrime(int num) {
if (num <= 1) {
return false; // 0 and 1 are not prime numbers
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false; // Found a divisor, not prime
}
}
return true; // No divisors found, it's prime
}
}
Program Structure and Execution
This Java program consists of a main class named PrimeChecker with two methods:
- main: The entry point of the program, where the number to be checked is defined. It calls the
checkPrimemethod and prints the result. - checkPrime: This method takes an integer as an input and checks if it is prime by testing for divisibility from 2 up to the square root of the number. It returns
trueif the number is prime andfalseotherwise.
How to Run the Program
- Make sure you have Java Development Kit (JDK) installed on your machine.
- Create a new file named
PrimeChecker.javaand copy the code provided above into this file. - Open a command prompt or terminal window.
- Navigate to the directory where you saved
PrimeChecker.java. - Compile the program using the command:
javac PrimeChecker.java - Run the compiled program using the command:
java PrimeChecker - Observe the output, which will indicate whether the defined number is prime.

