Java Program to Determine If a Number Is Prime
What Is a Prime Number?
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Classic examples include 2, 3, 5, 7, 11, 13, 17, ….
Key points:
- 0 and 1 are not prime.
- 2 is the only even prime number.
Java Program to Determine If a Number Is Prime
Algorithm overview:
- Check divisibility of the target number by all integers from 2 up to its half (inclusive). If any division yields a remainder of 0, the number is composite.
- Once a divisor is found, the loop can exit early to save time.
- If no divisor is found, the number is prime.
public class PrimeChecker {
public static void main(String[] args) {
int numberToCheck = 17; // change this value to test other numbers
boolean isPrime = true;
// Edge cases: 0 and 1 are not prime
if (numberToCheck < 2) {
isPrime = false;
} else {
for (int i = 2; i <= numberToCheck / 2; i++) {
int remainder = numberToCheck % i;
System.out.println(numberToCheck + " ÷ " + i + " = " + (numberToCheck / i) + " remainder " + remainder);
if (remainder == 0) {
isPrime = false;
break;
}
}
}
if (isPrime) {
System.out.println(numberToCheck + " is a prime number.");
} else {
System.out.println(numberToCheck + " is not a prime number.");
}
}
}
Sample Output
17 ÷ 2 = 8 remainder 1 17 ÷ 3 = 5 remainder 2 17 ÷ 4 = 4 remainder 1 17 ÷ 5 = 3 remainder 2 17 ÷ 6 = 2 remainder 5 17 ÷ 7 = 2 remainder 3 17 ÷ 8 = 2 remainder 1 17 is a prime number.
Try the program above to check any integer, or extend it to find all prime numbers between 1 and 100.
Java
- Java Hello World: Your First Program
- Java String.contains() Method: How to Check for Substrings – Practical Examples
- Constructor Overloading in Java – Explained with Practical Code Examples
- Java Multithreading Explained: Concepts, Lifecycle, and Practical Code Examples
- Java Program to List Prime Numbers from 1 to 100 – Step‑by‑Step Guide
- Generate Fibonacci Sequence in Java: For, While, and Recursive Examples
- Java Program to Identify Armstrong Numbers Using For Loop
- Java Palindrome Number Checker: Algorithms Using While and For Loops
- Insertion Sort Algorithm in Java: A Clear Example & Step‑by‑Step Guide
- Selection Sort in Java: Step‑by‑Step Example & Full Code