Skip to main content
Advertisement

4.2 Loops

Loops are used when a task needs to be performed repeatedly. They execute the statements within their block continuously as long as the given condition is true.

1. The for Loop

The for loop is primarily used when the exact number of iterations is already known. Composed of an initialization, a conditional expression, an increment/decrement expression, and the block to loop, it clearly lays out these three parts on a single line.

// Structure: for(initialization; condition; increment/decrement)
for (int i = 1; i <= 5; i++) {
System.out.println("Hello Java! " + i);
}

// Sum of numbers from 1 to 10
int sum = 0;
for(int i = 1; i <= 10; i++) {
sum += i; // Accumulate the value of i the each iteration
}
System.out.println("Sum: " + sum);

Enhanced for Statement

A syntax that allows you to write very concise code when iterating over all elements of an array or collection purely for the purpose of reading them. (Added in JDK 1.5)

int[] numbers = {10, 20, 30};

// Java's "Enhanced for loop"
for (int num : numbers) {
System.out.println(num); // Outputs 10, 20, and 30 sequentially
}

2. The while Loop

In contrast to the for loop, it is primarily used when the number of iterations is unknown and the repetition is dictated dynamically by a condition. That is, it continually executes the code in the block as long as the conditional expression is true.

int i = 5;

// Condition: As long as i is greater than 0
while(i > 0) {
System.out.println(i + " - Keep going!");
i--; // You must change the value within the block to eventually meet the exit condition.
}

Caution: Infinite Loops

If the condition is always true, the program will fall into an infinite loop that never terminates. Because the while loop requires the increment/decrement step inside its block, you must be careful not to omit it accidentally.

while(true) { // standard way to create an infinite loop
// Requires logic to 'break' based on a condition internally
}

3. The do-while Loop

A variant of the while loop, where it executes the block { } once first and then evaluates the condition. Therefore, it differentiates itself from the general while loop by guaranteeing execution at least once, even if the condition evaluates to false at the beginning.

int input = 0;
do {
// Guaranteed to execute once; subsequent loops depend on 'input'
System.out.println("Please enter a value. Enter 1 to exit.");
// input = ... logic to get input from user (e.g., using Scanner)
} while(input != 1);

This pattern acts advantageously when accepting user input where the data must be validated afterward.

Advertisement