Loops are fundamental control structures in programming that allow you to execute a block of code repeatedly. This is incredibly useful for tasks that involve iteration, such as processing lists of items, performing calculations multiple times, or waiting for a certain condition to be met.

In Java, there are three primary types of loops:

  1. while loop: Executes a block of code as long as a specified condition is true.

  2. for loop: A more compact loop structure often used when you know in advance how many times you want to iterate.

  3. do-while loop: Similar to the while loop, but guarantees that the block of code is executed at least once before checking the condition.

Let's explore each of these in detail.

1. The while Loop

The while loop is the simplest loop. It repeatedly executes a target statement as long as a given boolean condition remains true.

Syntax:

while (condition) {
    // code to be executed repeatedly
}

How it works:

  • The condition is evaluated before each execution of the loop body.

  • If condition is true, the code inside the curly braces {} is executed.

  • After the code inside the loop is executed, the condition is re-evaluated.

  • This process continues until the condition becomes false.

  • If the condition is false initially, the loop body will never be executed.

Example: Counting up to 5

// WhileLoopExample.java

public class WhileLoopExample {

public static void main(String[] args) {

int count = 1; // Initialize a counter variable


System.out.println("Starting while loop:");

while (count <= 5) { // Condition: continue as long as count is less than or equal to 5

System.out.println("Current count: " + count);

count++; // Increment the counter (important to avoid an infinite loop)

}

System.out.println("While loop finished. Final count: " + count);

}

}

Important Note: It is crucial to ensure that the condition inside a while loop eventually becomes false. Otherwise, you will create an infinite loop, where the program never terminates.

2. The for Loop

The for loop is ideal when you know exactly how many times you want to iterate, or when you need to iterate over a sequence with a clear starting point, ending point, and step.

Syntax:

for (initialization; condition; increment/decrement) {
    // code to be executed repeatedly
}

How it works:

  1. initialization: This statement is executed once at the beginning of the loop. It's typically used to declare and initialize a loop control variable.

  2. condition: This boolean expression is evaluated before each iteration. If true, the loop body executes. If false, the loop terminates.

  3. increment/decrement: This statement is executed after each iteration of the loop body. It's typically used to update the loop control variable.

Example: Counting up to 5 with a for loop

// ForLoopExample.java

public class ForLoopExample {

public static void main(String[] args) {

System.out.println("Starting for loop:");

// The loop initializes 'i' to 1, continues as long as 'i' is <= 5,

// and increments 'i' by 1 after each iteration.

for (int i = 1; i <= 5; i++) {

System.out.println("Current iteration (i): " + i);

}

System.out.println("For loop finished.");

}

}

Enhanced for Loop (For-Each Loop): Java also provides an enhanced for loop, or "for-each" loop, which is particularly useful for iterating over arrays and collections.

Syntax:

for (type element : collection) {
    // code to be executed for each element
}

Example: Iterating over an array

// ForEachLoopExample.java

public class ForEachLoopExample {

public static void main(String[] args) {

String[] fruits = {"Apple", "Banana", "Cherry", "Date"};


System.out.println("Iterating through fruits using for-each loop:");

for (String fruit : fruits) {

System.out.println("Fruit: " + fruit);

}

System.out.println("For-each loop finished.");

}

}

3. The do-while Loop

The do-while loop is similar to the while loop, but its key characteristic is that its block of code is guaranteed to execute at least once, because the condition is evaluated after the loop body.

Syntax:

do {
    // code to be executed at least once
} while (condition); // Note the semicolon here!

How it works:

  1. The code inside the do block is executed first.

  2. After the do block, the condition is evaluated.

  3. If condition is true, the loop continues, and the do block is executed again.

  4. This process repeats until the condition becomes false.

Example: User input validation (executes at least once)

// DoWhileLoopExample.java

import java.util.Scanner; // Import the Scanner class to read user input


public class DoWhileLoopExample {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in); // Create a Scanner object

int number;


System.out.println("Using do-while loop for input validation:");

do {

System.out.print("Enter an even number (or 0 to exit): ");

number = scanner.nextInt(); // Read integer input from the user


if (number % 2 != 0 && number != 0) { // Check if it's odd and not 0

System.out.println("That's an odd number! Please try again.");

}

} while (number % 2 != 0 || number == 0); // Continue if odd OR if it's 0 (to allow exit)

// Correction: The condition should be `number % 2 != 0` to continue for odd numbers.

// If the user enters 0, we want to exit. So let's adjust.

// Revised condition: continue if number is odd, and stop if even (or 0).

// Let's refine the example to make the exit clear.


// Corrected logic for a clear example:

do {

System.out.print("Enter a number greater than 10: ");

number = scanner.nextInt();

if (number <= 10) {

System.out.println("Number must be greater than 10. Try again.");

}

} while (number <= 10); // Loop continues as long as number is NOT greater than 10


System.out.println("You entered: " + number + ". Loop finished.");

scanner.close(); // Close the scanner to prevent resource leaks

}

}

Loop Control Statements: break and continue

Java provides two keywords to control the flow within loops:

  • break: Immediately terminates the loop and transfers control to the statement immediately following the loop.

  • continue: Skips the current iteration of the loop and proceeds with the next iteration.

Example: break and continue

// LoopControlExample.java

public class LoopControlExample {

public static void main(String[] args) {

System.out.println("--- Demonstrating 'break' ---");

for (int i = 1; i <= 10; i++) {

if (i == 6) {

System.out.println("Reached 6, breaking the loop.");

break; // Exit the loop entirely

}

System.out.println("Current number (break example): " + i);

}

System.out.println("Loop after break finished.\n");


System.out.println("--- Demonstrating 'continue' ---");

for (int i = 1; i <= 5; i++) {

if (i == 3) {

System.out.println("Skipping 3 using continue.");

continue; // Skip the rest of this iteration, go to the next

}

System.out.println("Current number (continue example): " + i);

}

System.out.println("Loop after continue finished.");

}

}

When to Use Which Loop?

  • for loop: Use when you know the exact number of iterations, or when you need to iterate through elements of an array or collection (especially with the enhanced for loop).

  • while loop: Use when the number of iterations is not known beforehand, and the loop needs to continue as long as a certain condition remains true.

  • do-while loop: Use when you need the loop body to execute at least once, regardless of the initial condition. This is often useful for input validation or menu-driven programs.

Understanding and effectively using loops is crucial for writing efficient and dynamic Java programs. Practice with these examples and try to create your own scenarios where loops would be beneficial!

Key Takeaways

  • Loops let you execute a block of code multiple times, automating repetitive tasks

  • While loops, for loops, and do-while loops

  • Executes a block of code as long as a specified condition is true

  • Works similarly to while loop, just more compact and when you know in advance how many times you want the code to execute

  • Runs like the while loop, but guarantees the code is run at least once before the condition is checked