Java Program to List Prime Numbers from 1 to 100 – Step‑by‑Step Guide
What is a Prime Number?
A prime number is a natural number greater than one that has no positive divisors other than 1 and itself. Examples include 2, 3, 5, 7, 11, 13, 17, and so on.
Important: 0 and 1 are not prime, and 2 is the sole even prime number.
Java Program to Print Prime Numbers Between 1 and 100
Below is a clear, commented Java program that enumerates all prime numbers from 1 to 100:
public class PrimeNumbersDemo {
public static void main(String[] args) {
int maxCheck = 100;
StringBuilder primes = new StringBuilder();
for (int i = 2; i <= maxCheck; i++) {
if (isPrime(i)) {
primes.append(i).append(' ');
}
}
System.out.println("Prime numbers from 1 to " + maxCheck + " are:");
System.out.println(primes.toString());
}
private static boolean isPrime(int number) {
if (number < 2) {
return false;
}
for (int i = 2; i <= number / 2; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
Expected Output
Prime numbers from 1 to 100 are: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Feel free to modify maxCheck to generate primes up to any limit.
Java
- Java Hello World: Your First Program
- Constructor Overloading in Java – Explained with Practical Code Examples
- Java Multithreading Explained: Concepts, Lifecycle, and Practical Code Examples
- Java Program to Determine If a Number Is Prime
- 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
- Master Bubble Sort in Java: Clear Example & Step‑by‑Step Walkthrough
- Insertion Sort Algorithm in Java: A Clear Example & Step‑by‑Step Guide
- Selection Sort in Java: Step‑by‑Step Example & Full Code