Java Loops
Introduction
A loop in Java is used to execute a block of code repeatedly as long as a specified condition is true.
Loops help us avoid writing the same code multiple times.
Example
Without a loop:
System.out.println("Hello"); System.out.println("Hello"); System.out.println("Hello"); System.out.println("Hello"); System.out.println("Hello");
With a loop:
for (int i = 1; i <= 5; i++) { System.out.println("Hello"); }
Both examples print Hello five times, but the loop makes the program shorter and easier to maintain.
Types of Loops in Java
Java mainly provides three types of loops:
- for loop
- while loop
- do-while loop
Java also provides an enhanced for loop (for-each loop), which is commonly used with arrays and collections.
| Loop | Condition Checked | Best Used When |
|---|---|---|
for | Before each iteration | Number of repetitions is known |
while | Before each iteration | Number of repetitions may not be known |
do-while | After each iteration | Code must execute at least once |
Enhanced for | Automatically | Traversing arrays/collections |
1. for Loop
The for loop is commonly used when we know how many times we want to execute a block of code.
Syntax
for (initialization; condition; update) { // statements }
Example
public class ForExample { public static void main(String[] args) { for (int i = 1; i <= 5; i++) { System.out.println(i); } } }
Output
1 2 3 4 5
How it works
Initialization ↓ Condition ↓ Statements ↓ Update ↓ Condition ↓ Repeat
2. while Loop
A while loop repeatedly executes a block of code as long as its condition is true.
Syntax
while (condition) { // statements }
Example
public class WhileExample { public static void main(String[] args) { int i = 1; while (i <= 5) { System.out.println(i); i++; } } }
Output
1 2 3 4 5
Important Point
The condition is checked before executing the loop body.
If the condition is false initially, the loop body will not execute even once.
3. do-while Loop
The do-while loop executes the block of code first and checks the condition afterward.
Syntax
do { // statements } while (condition);
Example
public class DoWhileExample { public static void main(String[] args) { int i = 1; do { System.out.println(i); i++; } while (i <= 5); } }
Output
1 2 3 4 5
Important Point
A do-while loop executes at least once, even if the condition is false.
Example:
int i = 10; do { System.out.println(i); } while (i < 5);
Output
10
The condition i < 5 is false, but 10 is printed once because the condition is checked after the loop body.
4. Enhanced for Loop
The enhanced for loop, also called the for-each loop, is used to access elements of arrays and collections.
Syntax
for (dataType variable : array) { // statements }
Example
public class ForEachExample { public static void main(String[] args) { int[] numbers = {10, 20, 30, 40, 50}; for (int number : numbers) { System.out.println(number); } } }
Output
10 20 30 40 50
Nested Loops
A loop inside another loop is called a nested loop.
Example
public class NestedLoop { public static void main(String[] args) { for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { System.out.println("i = " + i + ", j = " + j); } } } }
Output
i = 1, j = 1 i = 1, j = 2 i = 1, j = 3 i = 2, j = 1 i = 2, j = 2 i = 2, j = 3 i = 3, j = 1 i = 3, j = 2 i = 3, j = 3
Nested loops are commonly used for:
- Patterns
- Matrices
- Tables
- Two-dimensional arrays
Loop Control Statements
Java provides statements that control the execution of loops.
1. break
The break statement immediately terminates the loop.
Example
for (int i = 1; i <= 10; i++) { if (i == 5) { break; } System.out.println(i); }
Output
1 2 3 4
2. continue
The continue statement skips the current iteration and moves to the next iteration.
Example
for (int i = 1; i <= 5; i++) { if (i == 3) { continue; } System.out.println(i); }
Output
1 2 4 5
Example: Print Even Numbers
public class EvenNumbers { public static void main(String[] args) { for (int i = 1; i <= 10; i++) { if (i % 2 == 0) { System.out.println(i); } } } }
Output
2 4 6 8 10
Example: Sum of Numbers
public class SumExample { public static void main(String[] args) { int sum = 0; for (int i = 1; i <= 10; i++) { sum = sum + i; } System.out.println("Sum = " + sum); } }
Output
Sum = 55
Example: Multiplication Table
public class TableExample { public static void main(String[] args) { int number = 5; for (int i = 1; i <= 10; i++) { System.out.println(number + " x " + i + " = " + (number * i)); } } }
Output
5 x 1 = 5 5 x 2 = 10 5 x 3 = 15 5 x 4 = 20 5 x 5 = 25 5 x 6 = 30 5 x 7 = 35 5 x 8 = 40 5 x 9 = 45 5 x 10 = 50
Infinite Loop
An infinite loop is a loop that never ends because its condition always remains true.
Example:
while (true) { System.out.println("Hello"); }
This loop continues until the program is stopped.
Another example:
for (;;) { System.out.println("Hello"); }
Use infinite loops carefully.
Difference Between Loops
| Feature | for | while | do-while |
|---|---|---|---|
| Condition checked | Before | Before | After |
| Executes at least once | No | No | Yes |
| Initialization | Usually in loop | Usually before loop | Usually before loop |
| Update | Usually in loop | Usually inside body | Usually inside body |
| Best for | Known repetitions | Unknown repetitions | At least one execution |
Advantages of Loops
- Reduces code duplication
- Saves programming time
- Makes programs shorter
- Makes repetitive tasks easier
- Improves code readability
- Useful for processing arrays and collections
- Useful for mathematical calculations
Disadvantages of Loops
- Incorrect conditions can create infinite loops.
- Nested loops can make programs difficult to understand.
- Too many iterations can affect performance.
- Incorrect update statements can cause unexpected results.
Real-Life Examples of Loops
Loops are useful for:
- Printing student records
- Processing employee information
- Reading data from a file
- Calculating marks
- Displaying multiplication tables
- Searching data
- Processing arrays
- Repeating menu options
- Generating reports
Complete Example
public class LoopDemo { public static void main(String[] args) { System.out.println("Numbers from 1 to 5:"); for (int i = 1; i <= 5; i++) { System.out.println(i); } System.out.println("Even numbers:"); int number = 2; while (number <= 10) { System.out.println(number); number += 2; } System.out.println("Do-while example:"); int x = 1; do { System.out.println(x); x++; } while (x <= 3); } }
Summary
A loop is used to execute a block of Java code repeatedly.
The main types of loops are:
- for loop – useful when the number of repetitions is known.
- while loop – useful when the condition controls an unknown number of repetitions.
- do-while loop – executes the code at least once.
- enhanced for loop – useful for traversing arrays and collections.
Loop control statements such as break and continue provide additional control over loop execution.