Java ProgramsControl FlowPrint Even Numbers

Print Even Numbers in Java

beginner·  Control Flow  ·  Loops

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.

Input
n = 20
Output
2 4 6 8 10 12 14 16 18 20

Java Program

Java
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

2 4 6 8 10 12 14 16 18 20

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.

How It Works
  1. 1for (int i = 2; i <= n; i += 2) starts at the first even number and increases by 2 instead of 1.
  2. 2Because the step size is 2, every value i takes on is already even — there's no need to test i % 2 == 0 inside the loop.
  3. 3The loop stops once i passes n, the same bound check used to print a plain 1-to-n sequence.
For 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.

Complexity
Time Complexity: O(n)Space Complexity: O(1)

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

for loopstep incrementeven numbers

Approach 2: Java 8

Java
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

2 4 6 8 10 12 14 16 18 20

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.

How It Works
  1. 1IntStream.rangeClosed(1, n) generates every number in the range, both even and odd.
  2. 2.filter(i -> i % 2 == 0) keeps only the values divisible by 2.
  3. 3.forEach(System.out::println) prints each surviving value in order.
For 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'.

Complexity
Time Complexity: O(n)Space Complexity: O(1)

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.

Key Concepts

StreamIntStream.rangeClosed()filter()

Related Programs