Java Loops

Java Loops – In Java, loops are control flow statements that repeatedly execute a block of code as long as a specified condition is true. They are essential for tasks such as iterating over arrays, processing collections, and executing repetitive tasks.

This tutorial covers various types of loops in Java, including:

  1. For Loop – Detailed syntax, usage, and examples.
  2. While Loop – Detailed syntax, usage, and examples.
  3. Do-While Loop – Detailed syntax, usage, and examples.
  4. Enhanced For Loop – Detailed syntax, usage, and examples.
  5. Nested Loops – How to use loops within loops.

Each section includes detailed descriptions, syntax, example programs (using Example as the class name), expected output, and explanations to help you master looping in Java.

1 For Loop

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

Syntax:

</>
Copy
for(initialization; condition; update) {
    // code block to be executed
}

Example: This program prints numbers 1 to 5 using a for loop.

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

Output:

Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5

Explanation: The loop initializes i to 1, checks if i is less than or equal to 5, prints the current iteration, and increments i by 1 after each iteration.

2 While Loop

The while loop executes a block of code as long as the specified condition remains true. It is useful when the number of iterations is not known in advance.

Syntax:

</>
Copy
while(condition) {
    // code block to be executed
}

Example: This program prints numbers 1 to 5 using a while loop.

</>
Copy
public class Example {
    public static void main(String[] args) {
        int i = 1;
        while (i <= 5) {
            System.out.println("Count: " + i);
            i++;
        }
    }
}

Output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

Explanation: The loop starts with i set to 1 and continues to execute as long as i is less than or equal to 5. After each iteration, i is incremented by 1.

3 Do-While Loop

The do-while loop is similar to the while loop, but it guarantees that the code block will be executed at least once before the condition is tested.

Syntax:

</>
Copy
do {
    // code block to be executed
} while (condition);

Example: This program prints numbers 1 to 5 using a do-while loop.

</>
Copy
public class Example {
    public static void main(String[] args) {
        int i = 1;
        do {
            System.out.println("Value: " + i);
            i++;
        } while (i <= 5);
    }
}

Output:

Value: 1
Value: 2
Value: 3
Value: 4
Value: 5

Explanation: The do-while loop executes the code block first, then checks the condition. This ensures that the code inside the loop is executed at least once even if the condition is false initially.

4 Enhanced For Loop

The enhanced for loop, also known as the for-each loop, is used for iterating over arrays or collections. It provides a simpler and more readable syntax when you do not need to modify the array or collection.

Syntax:

</>
Copy
for(dataType item : array) {
    // code block to be executed
}

Example: This program iterates through an array of integers and prints each element.

</>
Copy
public class Example {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};
        for (int num : numbers) {
            System.out.println("Number: " + num);
        }
    }
}

Output:

Number: 10
Number: 20
Number: 30
Number: 40
Number: 50

Explanation: The enhanced for loop automatically iterates over each element in the numbers array and assigns it to the variable num during each iteration.

5 Nested Loops

Nested loops are loops inside other loops. They are useful for iterating over multi-dimensional arrays or performing repeated operations within each iteration of an outer loop.

Example: This program uses nested loops to print a multiplication table for numbers 1 to 3.

</>
Copy
public class Example {
    public static void main(String[] args) {
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 3; j++) {
                System.out.print((i * j) + " ");
            }
            System.out.println();
        }
    }
}

Output:

1 2 3 
2 4 6 
3 6 9

Explanation: The outer loop iterates through the numbers 1 to 3. For each iteration of the outer loop, the inner loop iterates through the numbers 1 to 3, multiplying the outer loop variable i by the inner loop variable j and printing the product.

Conclusion

In this Java Tutorial, we explored various types of loops in Java. We covered the syntax and usage of the for, while, do-while, and enhanced for-each loops, along with an example of nested loops. Understanding these looping constructs is fundamental for performing repetitive tasks and iterating through data structures in Java.