Print Prime Numbers in a Range in Java
Problem
Listing primes in a range means checking every number between two bounds and keeping only the ones that are prime, rather than testing just one candidate.
Given a lower and upper bound, list every prime number found between them.
Java Program
public class PrintPrimesInRange {
static boolean isPrime(int n) {
if (n < 2) return false;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) return false; // found a divisor, not prime
}
return true;
}
public static void main(String[] args) {
int low = 10, high = 30;
StringBuilder result = new StringBuilder();
for (int i = low; i <= high; i++) {
if (isPrime(i)) { // reuse the same primality check for every candidate
if (result.length() > 0) result.append(", ");
result.append(i);
}
}
System.out.println(result);
}
}Output
Core Logic
Testing every number in the range for primality, and collecting the ones that pass, lists every prime between the two bounds.
- 1
isPrime(n)is a helper method testing divisors only up to√n, the standard efficient primality check. - 2The loop tries every
ifromlowtohigh, inclusive. - 3
isPrime(i)checks whether the current number qualifies. - 4Each prime found is appended to the result, separated by commas.
10 to 30, the scan finds six primes: 11, 13, 17, 19, 23, and 29.Key Point: Reusing the same isPrime() helper used to check a single number is what makes this a natural extension — listing a range is just calling the same check repeatedly.
Why: Each of the n numbers in the range triggers its own O(√n) primality check, and the result string can grow to hold every prime found.
Key Concepts
Approach 2: Java 8
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class PrintPrimesInRangeStream {
static boolean isPrime(int n) {
if (n < 2) return false;
return IntStream.rangeClosed(2, (int) Math.sqrt(n)).noneMatch(i -> n % i == 0);
}
public static void main(String[] args) {
int low = 10, high = 30;
// Keeps only the numbers that pass the primality check, then joins them
String result = IntStream.rangeClosed(low, high)
.filter(PrintPrimesInRangeStream::isPrime)
.mapToObj(String::valueOf)
.collect(Collectors.joining(", "));
System.out.println(result);
}
}
Output
Core Logic
The same primality check can filter a stream of the range's numbers directly, then join the survivors.
- 1
IntStream.rangeClosed(low, high)generates every number in the range. - 2
.filter(...)keeps only the numbers that pass the primality check. - 3
.mapToObj(String::valueOf)converts each survivingintinto aString. - 4
.collect(Collectors.joining(", "))joins the primes into the final comma-separated result.
Key Point: The filter condition is the exact same primality check the loop version uses — streams just change how the range is walked and the results collected.
Why: The stream still runs the same O(√n) primality check per number, and Collectors.joining() builds a result string holding every prime found.