NBKRIST JavaHub – Java Iteration Statements

Java Iteration Statements – Complete Beginner Guide

Iteration statements allow Java programs to repeat tasks automatically. Loops are essential for performing repetitive tasks efficiently.

1. Introduction to Iteration

Iteration means executing a block of code repeatedly. Java provides multiple loop structures, each useful for different scenarios.

Main loops: while, do-while, for, nested for, for-each.

2. The while Expression

The while loop checks the condition first and executes the block only while the condition is true.

int i = 1; while(i <= 5){ System.out.println(i); i++; }
1
2
3
4
5

3. The do–while Loop

The do-while loop executes at least once, because the condition is checked after running the loop body.

int x = 1; do{ System.out.println(x); x++; }while(x <= 3);
1
2
3

4. The for Loop

The for loop is used when the number of iterations is known in advance.

for(int k = 1; k <= 5; k++){ System.out.println(k); }
1
2
3
4
5

5. Nested for Loop

Using a loop inside another loop allows multi-level repetition. Useful in matrix operations and pattern printing.

for(int i = 1; i <= 3; i++){ for(int j = 1; j <= 3; j++){ System.out.println(i + \" \" + j); } }
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

6. For–Each Loop

The for-each loop is used for easy traversal of arrays and collections.

int nums[] = {10, 20, 30}; for(int n : nums){ System.out.println(n); }
10
20
30

7. The break Statement

break immediately stops the loop execution.

for(int i = 1; i <= 5; i++){ if(i == 3) break; System.out.println(i); }
1
2

8. The continue Statement

continue skips the current loop iteration and proceeds with the next.

for(int i = 1; i <= 5; i++){ if(i == 3) continue; System.out.println(i); }
1
2
4
5

Practice Questions – Click to Reveal Answers

1️⃣ Difference between while and do–while?
while checks before; do–while checks after, so it executes at least once.
2️⃣ Best loop for fixed number of iterations?
The for loop.
3️⃣ What does break do?
Stops the loop immediately.
4️⃣ What does continue do?
Skips the current iteration.
5️⃣ What is a nested loop?
A loop inside another loop.

Quick Summary