CS Engineering Gyan

Loops in Java

Many programming tasks involve repeating the same action multiple times, such as printing a list of numbers, processing every item in a collection, or checking a condition repeatedly until it changes. Writing the same line of code again and again for each repetition would be inefficient and difficult to maintain, which is exactly the problem loops are designed to solve.

Java provides several types of loops, each suited to slightly different situations. Some loops are ideal when you know exactly how many times a task should repeat, while others are better suited when the number of repetitions depends on a condition that may change during execution.

In this tutorial, you will learn how the for loop, while loop, do-while loop, and enhanced for loop work, along with how the break and continue statements can be used to control loop behavior more precisely.


What is a Loop in Java?

A loop is a control structure that repeats a block of code as long as a specified condition remains true. Once the condition becomes false, the loop stops, and the program continues with the code that follows it.

Example

public class LoopExample {

    public static void main(String[] args) {

        String channel = "CS Engineering Gyan";

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

            System.out.println(channel + " video number " + i + " uploaded.");

        }

    }

}

Output

CS Engineering Gyan video number 1 uploaded.

CS Engineering Gyan video number 2 uploaded.

CS Engineering Gyan video number 3 uploaded.

Instead of writing the same print statement three separate times, the loop repeats it automatically, adjusting the value of i with each repetition.


The for Loop

The for loop is typically used when the number of repetitions is known in advance. It combines initialization, condition checking, and updating into a single, compact line, making it one of the most commonly used loops in Java.

Syntax

for (initialization; condition; update) {

    // code to repeat

}

Example

public class ForLoopExample {

    public static void main(String[] args) {

        String channel = "CS Engineering Gyan";

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

            System.out.println(channel + " weekly upload " + week + " completed.");

        }

    }

}

Output

CS Engineering Gyan weekly upload 1 completed.

CS Engineering Gyan weekly upload 2 completed.

CS Engineering Gyan weekly upload 3 completed.

CS Engineering Gyan weekly upload 4 completed.

CS Engineering Gyan weekly upload 5 completed.

In this example, week starts at 1, the loop continues as long as it is less than or equal to 5, and its value increases by 1 after each repetition, until the condition becomes false.


The while Loop

The while loop is useful when the number of repetitions is not known beforehand and instead depends on a condition that may change while the program is running. The condition is checked before each repetition, meaning the loop may not execute at all if the condition starts out false.

Syntax

while (condition) {

    // code to repeat

}

Example

public class WhileLoopExample {

    public static void main(String[] args) {

        String channel = "CS Engineering Gyan";

        int subscribers = 96000;

        while (subscribers < 100000) {

            subscribers += 1000;

            System.out.println(channel + " subscribers now: " + subscribers);

        }

    }

}

Output

CS Engineering Gyan subscribers now: 97000

CS Engineering Gyan subscribers now: 98000

CS Engineering Gyan subscribers now: 99000

CS Engineering Gyan subscribers now: 100000

Here, the loop keeps running and increasing the subscriber count until it reaches 100000, at which point the condition becomes false and the loop stops automatically.


The do-while Loop

The do-while loop is similar to the while loop, but with one important difference: the condition is checked after the code block runs, not before. This guarantees that the loop's body executes at least once, even if the condition is false from the very beginning.

Syntax

do {

    // code to repeat

} while (condition);

Example

public class DoWhileExample {

    public static void main(String[] args) {

        String channel = "CS Engineering Gyan";

        int videoCount = 0;

        do {

            videoCount++;

            System.out.println(channel + " published video " + videoCount);

        } while (videoCount < 3);

    }

}

Output

CS Engineering Gyan published video 1

CS Engineering Gyan published video 2

CS Engineering Gyan published video 3

The do-while loop is particularly useful in situations such as menu-driven programs, where an action should happen at least once before checking whether it should be repeated again.


while vs do-while Loop

while Loop do-while Loop
Condition is checked before the loop body executes. Condition is checked after the loop body executes.
The loop body may not execute at all if the condition is false initially. The loop body always executes at least once.
Commonly used when the number of repetitions depends entirely on a condition. Commonly used when at least one execution is required regardless of the condition.

The Enhanced for Loop

Java provides an enhanced for loop, also known as a for-each loop, which is specifically designed for iterating through elements of arrays or collections. It removes the need to manually manage an index variable, making the code shorter and easier to read.

Syntax

for (dataType element : collection) {

    // code to execute for each element

}

Example

public class EnhancedForExample {

    public static void main(String[] args) {

        String channel = "CS Engineering Gyan";

        String[] playlists = {"Java Basics", "Data Structures", "DBMS", "Operating Systems"};

        System.out.println(channel + " current playlists:");

        for (String playlist : playlists) {

            System.out.println("- " + playlist);

        }

    }

}

Output

CS Engineering Gyan current playlists:

- Java Basics

- Data Structures

- DBMS

- Operating Systems

The enhanced for loop automatically moves through each element in the array, from the first to the last, without requiring you to track the index or the length of the array manually.


The break Statement

The break statement is used to exit a loop immediately, even if the loop's condition would otherwise still be true. This is useful when a specific situation is reached and there is no need to continue checking further repetitions.

Example

public class BreakExample {

    public static void main(String[] args) {

        String channel = "CS Engineering Gyan";

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

            if (video == 5) {

                System.out.println(channel + " stopped uploads at video " + video);

                break;

            }

            System.out.println(channel + " uploaded video " + video);

        }

    }

}

Output

CS Engineering Gyan uploaded video 1

CS Engineering Gyan uploaded video 2

CS Engineering Gyan uploaded video 3

CS Engineering Gyan uploaded video 4

CS Engineering Gyan stopped uploads at video 5

As soon as the condition inside the if statement becomes true, the break statement immediately ends the loop, skipping any remaining repetitions that would have otherwise occurred.


The continue Statement

The continue statement works differently from break. Instead of ending the loop completely, it skips the rest of the current repetition and moves directly to the next one, without stopping the loop altogether.

Example

public class ContinueExample {

    public static void main(String[] args) {

        String channel = "CS Engineering Gyan";

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

            if (video == 3) {

                continue;

            }

            System.out.println(channel + " processed video " + video);

        }

    }

}

Output

CS Engineering Gyan processed video 1

CS Engineering Gyan processed video 2

CS Engineering Gyan processed video 4

CS Engineering Gyan processed video 5

Notice that video 3 is skipped entirely, but the loop continues running normally for the remaining values, unlike break, which would have stopped the loop completely at that point.


Nested Loops

Java also allows loops to be placed inside other loops, a structure known as a nested loop. This is often used when working with grid-like data or when repeating an entire sequence of steps multiple times.

Example

public class NestedLoopExample {

    public static void main(String[] args) {

        String channel = "CS Engineering Gyan";

        for (int week = 1; week <= 2; week++) {

            System.out.println(channel + " week " + week + " schedule:");

            for (int day = 1; day <= 3; day++) {

                System.out.println("  Day " + day + ": New video uploaded");

            }

        }

    }

}

Output

CS Engineering Gyan week 1 schedule:

  Day 1: New video uploaded

  Day 2: New video uploaded

  Day 3: New video uploaded

CS Engineering Gyan week 2 schedule:

  Day 1: New video uploaded

  Day 2: New video uploaded

  Day 3: New video uploaded

In this example, the outer loop controls the number of weeks, while the inner loop runs completely for each single repetition of the outer loop, resulting in a structured, repeated pattern of output.


Choosing the Right Loop

Situation Recommended Loop
Number of repetitions is known in advance. for loop
Repetition depends on a condition that may change over time. while loop
Code must run at least once regardless of the condition. do-while loop
Iterating through every element of an array or collection. enhanced for loop

Best Practices While Using Loops


Common Mistakes Beginners Make

Mistake Correct Practice
Forgetting to update the loop variable, causing an infinite loop. Always ensure the update statement changes the condition over time.
Using a semicolon accidentally after the for loop declaration. Avoid placing a semicolon right after the loop's closing parenthesis.
Confusing when to use break versus continue. Use break to exit the loop completely, and continue to skip only the current repetition.
Using a while loop when a do-while loop is actually required. Use do-while when the code must execute at least once before checking the condition.

Frequently Asked Interview Questions

  1. What is the main purpose of a loop in Java?
    A loop allows a block of code to repeat automatically as long as a specified condition remains true.
  2. What is the difference between a for loop and a while loop?
    A for loop is generally used when the number of repetitions is known, while a while loop is used when repetition depends on a changing condition.
  3. Why does a do-while loop always execute at least once?
    Because its condition is checked after the loop body runs, not before.
  4. What is the enhanced for loop used for?
    It is used to iterate through elements of arrays or collections without manually managing an index.
  5. What is the difference between break and continue statements?
    Break exits the loop completely, while continue skips only the current repetition and moves to the next one.
  6. What causes an infinite loop in Java?
    An infinite loop occurs when the loop's condition never becomes false, often due to a missing or incorrect update statement.
  7. What is a nested loop?
    A nested loop is a loop placed inside another loop, often used for working with grid-like or repeated structured data.
  8. Can a for loop be used without an initialization or update statement?
    Yes, all three parts of a for loop are optional, though the semicolons separating them must still be included.

Summary

Loops allow Java programs to repeat tasks efficiently without duplicating code, making them essential for handling repetitive operations such as processing lists, generating patterns, or waiting for a condition to change. The for loop works best when the number of repetitions is known in advance, while the while and do-while loops handle situations where repetition depends on a condition evaluated during execution.

The enhanced for loop further simplifies working with arrays and collections, while the break and continue statements provide additional control over how a loop behaves during execution. Together, these tools give you the ability to build programs that can process data efficiently, regardless of how many times a particular task needs to be repeated.

With a solid understanding of loops, you are now ready to explore arrays, which allow you to store and manage multiple related values using loops to process them efficiently.


← Previous: Conditional Statements Next: Arrays in Java →

Home Visit Our YouTube Channel