Write a Program to Check if a Number is Prime in Java
In this tutorial, you will learn how to write a Java program to check whether a number is prime or not. We’ll go through everything step-by-step, with simple explanations and a beginner-friendly approach.
π§ What is a Prime Number?
A prime number is a natural number greater than 1 that has only two factors: 1 and itself.
β Examples of Prime Numbers:
-
2, 3, 5, 7, 11, 13...
β Not Prime:
-
1 (has only one factor)
-
Google Advertisement
4 (has three factors: 1, 2, 4)
-
9 (has three factors: 1, 3, 9)
π§Ύ Java Program to Check if a Number is Prime
import java.util.Scanner;
public class PrimeCheck {
public static void main(String[] args) {
// Step 1: Create a Scanner object to get input from the user
Scanner sc = new Scanner(System.in);
// Step 2: Ask the user to enter a number
System.out.print("Enter a number: ");
int num = sc.nextInt();
// Step 3: Handle edge cases
if (num <= 1) {
System.out.println(num + " is not a prime number.");
} else {
boolean isPrime = true;
// Step 4: Check divisibility from 2 to square root of the number
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
// Step 5: Print result
if (isPrime) {
System.out.println(num + " is a prime number.");
} else {
System.out.println(num + " is not a prime number.");
}
}
// Step 6: Close the Scanner
sc.close();
}
}
π§΅ Step-by-Step Explanation:
β Step 1: Import Scanner Class
import java.util.Scanner;
We need Scanner
to read user input.
β Step 2: Take Input from the User
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
We prompt the user to enter a number and store it in variable num
.
β Step 3: Handle Special Cases
if (num <= 1) {
System.out.println(num + " is not a prime number.");
}
We check if the number is less than or equal to 1. These are not prime numbers.
β Step 4: Check for Divisibility
-
Google Advertisement
We loop from 2 to the square root of the number.
-
If any number divides
num
evenly (num % i == 0
), then it's not prime. -
We use
Math.sqrt(num)
for better performance (instead of checking up tonum - 1
).
β Step 5: Display the Result
β Step 6: Close Scanner
Always close the Scanner
object to avoid memory leaks.
π― Sample Output:
π Why Use Math.sqrt(num)
in the Loop?
Because if a number n
is divisible by some number a
, then it is also divisible by b = n/a
. So, if a <= sqrt(n)
, then b >= sqrt(n)
.
By checking only up to sqrt(n)
, we can reduce the number of operations, making the program more efficient.
π Conclusion
You have now learned:
-
What a prime number is
-
How to take input in Java
-
How to check if a number is prime using a
for
loop -
Why we use
Math.sqrt(num)
for optimization
This is a very important concept for Java beginners and is often asked in interviews and coding tests.