Java loops


In Java, loops are control structures that allow you to execute a block of code repeatedly based on a specified condition. They are fundamental to programming as they enable you to perform repetitive tasks efficiently. Java provides several types of loops, each suited for different scenarios.

Types of Loops in Java

  1. for Loop
  2. while Loop
  3. do-while Loop
  4. for-each Loop (Enhanced for Loop)

1. For Loop

The for loop is used when the number of iterations is known beforehand. It consists of three parts: initialization, condition, and increment/decrement.

Syntax:

for (initialization; condition; update) { // Block of code to be executed }

Example:

public class ForLoopExample { public static void main(String[] args) { for (int i = 0; i < 5; i++) { System.out.println("Iteration: " + i); } } }

Output:

Iteration: 0 Iteration: 1 Iteration: 2 Iteration: 3 Iteration: 4

2. While Loop

The while loop is used when the number of iterations is not known and depends on a condition. The loop continues as long as the condition is true.

Syntax:

while (condition) { // Block of code to be executed }

Example:

public class WhileLoopExample { public static void main(String[] args) { int i = 0; while (i < 5) { System.out.println("Iteration: " + i); i++; } } }

Output:

Iteration: 0 Iteration: 1 Iteration: 2 Iteration: 3 Iteration: 4

3. Do-While Loop

The do-while loop is similar to the while loop, but it guarantees that the block of code will be executed at least once, as the condition is checked after the execution.

Syntax:

do { // Block of code to be executed } while (condition);

Example:

public class DoWhileLoopExample { public static void main(String[] args) { int i = 0; do { System.out.println("Iteration: " + i); i++; } while (i < 5); } }

Output:

Iteration: 0 Iteration: 1 Iteration: 2 Iteration: 3 Iteration: 4

4. For-Each Loop (Enhanced For Loop)

The for-each loop is specifically designed to iterate over arrays and collections. It simplifies the code when you don't need the index of the elements.

Syntax:

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

Example:

public class ForEachLoopExample { public static void main(String[] args) { String[] fruits = {"Apple", "Banana", "Cherry"}; for (String fruit : fruits) { System.out.println(fruit); } } }

Output:

Apple Banana Cherry

Summary

Loops in Java are essential for executing repetitive tasks and controlling the flow of execution based on conditions. Each loop type is suited for specific situations, whether you know the number of iterations in advance (for loop), want to execute a block while a condition holds true (while loop), or ensure at least one execution regardless of the condition (do-while loop). The enhanced for loop provides a convenient way to iterate over collections and arrays. Understanding how to use loops effectively is crucial for writing efficient and clean Java programs.