Print Even Numbers in Java
Problem
Even numbers are every other integer starting from 2, so a loop can generate them directly by stepping by 2 instead of checking each number individually.
Given a number n, print every even number from 2 up to n.
Java Program
public class PrintEvenNumbers {
public static void main(String[] args) {
int n = 20;
for (int i = 2; i <= n; i += 2) {
System.out.println(i);
}
}
}Output
Core Logic
Starting the counter at 2 and stepping forward by 2 each time lands on every even number directly, without ever visiting an odd one.
- 1
for (int i = 2; i <= n; i += 2)starts at the first even number and increases by2instead of1. - 2Because the step size is 2, every value
itakes on is already even — there's no need to testi % 2 == 0inside the loop. - 3The loop stops once
ipassesn, the same bound check used to print a plain 1-to-n sequence.
n = 20, the loop starts at 2 and lands on 4, 6, 8, and so on, up through 20.Key Point: Stepping by 2 does half the work of a 1-to-n loop with a modulo check inside it — every iteration here produces an even number, instead of half the iterations being wasted on odd ones.
Why: The loop runs once per even number in the range, a count proportional to n, printing one value each with no growing storage.
Key Concepts
Approach 2: Java 8
import java.util.stream.IntStream;
public class PrintEvenNumbersStream {
public static void main(String[] args) {
int n = 20;
IntStream.rangeClosed(1, n).filter(i -> i % 2 == 0).forEach(System.out::println);
}
}
Output
Core Logic
Filtering a full 1-to-n stream down to the even values expresses the same idea as a pipeline, at the cost of visiting the odd numbers just to discard them.
- 1
IntStream.rangeClosed(1, n)generates every number in the range, both even and odd. - 2
.filter(i -> i % 2 == 0)keeps only the values divisible by 2. - 3
.forEach(System.out::println)prints each surviving value in order.
n = 20, the filtered stream keeps 2, 4, 6, ..., 20 — the same ten values the step-by-2 loop produces.Key Point: Unlike the loop's step-by-2 technique, this version still generates and discards every odd number along the way — a reasonable trade for how directly it reads as 'keep only the even ones'.
Why: The stream visits all n numbers in the range to filter them, twice the work of stepping by 2 directly, though still linear in n.