Java Tutorial 0/145 lessons ~6 min read Lesson 14

    Loops

    java loops for while do-while for-each enhanced break continue nested infinite loop iteration array collection

    Course progress0%
    Focus
    21 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    In the previous lesson, you learned how Java makes decisions using if-else and switch statements.

    However, many real-world applications require executing the same block of code repeatedly.

    Imagine:

    • Printing invoices for 100 customers
    • Reading thousands of records from a database
    • Processing files line by line
    • Validating multiple user inputs
    • Iterating through collections

    Writing the same code repeatedly is inefficient and difficult to maintain.

    Java provides loops to automate repetitive tasks.

    A loop executes a block of code multiple times until a specified condition becomes false.

    In this lesson, you'll learn:

    • Why loops are needed
    • Types of loops
    • for loop
    • while loop
    • do-while loop
    • Enhanced for loop (For-Each)
    • Nested loops
    • Infinite loops
    • Loop control statements (break & continue)
    • Real-world examples
    • Best practices
    • Common mistakes
    • Hands-on exercises
    • Professional interview questions

    What is a Loop?

    A loop repeatedly executes a block of code while a condition remains true.

    Instead of writing:

    java
    System.out.println("Welcome");
    System.out.println("Welcome");
    System.out.println("Welcome");
    System.out.println("Welcome");
    System.out.println("Welcome");

    Use a loop:

    java
    for (int i = 1; i <= 5; i++) {
    System.out.println("Welcome");
    }

    Output:

    Welcome
    Welcome
    Welcome
    Welcome
    Welcome

    Types of Loops in Java

    Java provides four looping mechanisms:

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

    Each serves different use cases.

    The for Loop

    The for loop is ideal when the number of iterations is known.

    Syntax:

    java
    for(initialization; condition; update) {
    // Code
    }

    Example:

    java
    for (int i = 1; i <= 5; i++) {
    System.out.println(i);
    }

    Output:

    1
    2
    3
    4
    5

    How a for Loop Works

    Execution order:

    1. Initialization executes once.
    2. Condition is checked.
    3. Loop body executes.
    4. Update expression executes.
    5. Repeat until the condition becomes false.

    Flow:

    Initialization
    Condition
    True
    Execute Body
    Update
    Condition Again

    The while Loop

    Use a while loop when the number of iterations is unknown.

    Syntax:

    java
    while(condition) {
    // Code
    }

    Example:

    java
    int count = 1;
    while (count <= 5) {
    System.out.println(count);
    count++;
    }

    Output:

    1
    2
    3
    4
    5

    The do-while Loop

    A do-while loop executes the code at least once, even if the condition is false.

    Syntax:

    java
    do {
    // Code
    } while(condition);

    Example:

    java
    int number = 1;
    do {
    System.out.println(number);
    number++;
    } while (number <= 5);

    Output:

    1
    2
    3
    4
    5

    Difference Between while and do-while

    whiledo-while
    Checks condition firstExecutes first, checks later
    May execute zero timesExecutes at least once

    Enhanced for Loop (For-Each)

    The enhanced for loop is used to iterate through arrays and collections.

    Example:

    java
    String[] fruits = {"Apple", "Banana", "Orange"};
    for (String fruit : fruits) {
    System.out.println(fruit);
    }

    Output:

    Apple
    Banana
    Orange

    Advantages:

    • Cleaner syntax
    • No index management
    • Less error-prone

    Nested Loops

    A loop inside another loop is called a nested loop.

    Example:

    java
    for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
    System.out.print("* ");
    }
    System.out.println();
    }

    Output:

    * * *
    * * *
    * * *

    Nested loops are commonly used for matrices, tables, and patterns.

    Infinite Loops

    A loop that never terminates is called an infinite loop.

    Example:

    java
    while (true) {
    System.out.println("Running...");
    }

    Use infinite loops carefully in servers, event listeners, or applications waiting for events.

    Using break

    The break statement immediately exits the loop.

    Example:

    java
    for (int i = 1; i <= 10; i++) {
    if (i == 6) {
    break;
    }
    System.out.println(i);
    }

    Output:

    1
    2
    3
    4
    5

    Using continue

    The continue statement skips the current iteration and proceeds to the next one.

    Example:

    java
    for (int i = 1; i <= 5; i++) {
    if (i == 3) {
    continue;
    }
    System.out.println(i);
    }

    Output:

    1
    2
    4
    5

    Real-World Example: ATM PIN Validation

    java
    int attempts = 0;
    while (attempts < 3) {
    System.out.println("Enter PIN");
    attempts++;
    }

    Real-World Example: Processing Orders

    java
    String[] orders = {"Laptop", "Mobile", "Keyboard"};
    for (String order : orders) {
    System.out.println("Processing: " + order);
    }

    Best Practices

    • Use for when the iteration count is known.
    • Use while when the iteration count depends on a condition.
    • Use do-while when the loop must execute at least once.
    • Prefer the enhanced for loop for arrays and collections when you don't need the index.
    • Keep loop bodies small and readable.
    • Avoid unnecessary nested loops for better performance.

    Common Mistakes

    Forgetting to Update the Loop Variable

    java
    while (i < 5) {
    System.out.println(i);
    }

    This creates an infinite loop.

    Wrong Loop Condition

    Using < instead of <= (or vice versa) may result in missing or extra iterations.

    Modifying Collections Incorrectly

    Changing a collection while using an enhanced for loop may throw a ConcurrentModificationException.

    Deeply Nested Loops

    Excessive nesting reduces readability and may affect performance.

    Hands-on Exercise

    Create a Java program that:

    1. Prints numbers from 1 to 100 using a for loop.
    2. Prints even numbers using a while loop.
    3. Demonstrates a do-while loop with user input.
    4. Uses an enhanced for loop to print an array of employee names.
    5. Uses nested loops to print a multiplication table.
    6. Demonstrates the use of break and continue.
    7. Creates a simple menu that repeats until the user selects "Exit".

    Summary

    Loops are one of the most fundamental programming constructs in Java. They eliminate repetitive code, improve readability, and make programs scalable. Choosing the right type of loop depends on whether the number of iterations is known, unknown, or guaranteed to execute at least once.

    Key Takeaways

    • Loops automate repetitive tasks.
    • for loops are best for fixed iterations.
    • while loops are ideal for condition-based repetition.
    • do-while loops execute at least once.
    • Enhanced for loops simplify array and collection traversal.
    • break exits a loop immediately.
    • continue skips the current iteration.
    • Nested loops are useful for matrices and pattern generation.

    Professional Interview Questions

    1What is the difference between for, while, and do-while loops?

    Professional Answer

    A for loop is preferred when the number of iterations is known in advance. A while loop is used when the loop depends on a condition that may change dynamically. A do-while loop guarantees at least one execution because the condition is evaluated after the loop body.

    Follow-up Questions

    • When would you use a do-while loop?
    • Can a while loop execute zero times?

    Interview Tip: Explain that selecting the appropriate loop improves readability and clearly expresses the program's intent.

    2What is the difference between break and continue?

    Professional Answer

    The break statement immediately terminates the loop, while the continue statement skips the current iteration and proceeds with the next iteration.

    Follow-up Questions

    • Can break be used in a switch statement?
    • Can continue be used outside loops?

    Interview Tip: Mention that excessive use of break and continue may reduce code readability.

    3What is the Enhanced for Loop?

    Professional Answer

    The enhanced for loop, also known as the for-each loop, simplifies iterating over arrays and collections. It removes the need for index management, resulting in cleaner and less error-prone code.

    Follow-up Questions

    • Can you modify the collection while using a for-each loop?
    • When is a traditional for loop more suitable?

    Interview Tip: State that the enhanced for loop is ideal for read-only traversal, while a traditional for loop is preferred when index access or element modification is required.

    Ready to mark this lesson complete?Track your journey across the entire course.