Java: Loops

Loops allow programs to repeat certain operations. This lesson covers the loop structures in Java.

1. for Loop

The for loop is the most commonly used loop structure, ideal when the number of iterations is known.

(1) Syntax

TEXT 📖 Display only
for (initialization; condition; update) {
    // Loop body
}

▶ Example: Print 1 to 10

JAVA
public class ForDemo {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            System.out.println(i);
        }
    }
}
▶ Try it Yourself

(2) Execution Flow

TEXT 📖 Display only
1. Execute initialization (int i = 1)
2. Check condition (i <= 10)
3. If condition is true, execute loop body
4. Execute update (i++)
5. Go back to step 2

▶ Example: Sum of 1 to 100

JAVA
public class SumDemo {
    public static void main(String[] args) {
        int sum = 0;
        
        for (int i = 1; i <= 100; i++) {
            sum += i;
        }
        
        System.out.println("Sum of 1 to 100: " + sum);  // 5050
    }
}
▶ Try it Yourself

2. while Loop

The while loop is ideal when the number of iterations is unknown.

(1) Syntax

JAVA
while (condition) {
    // Loop body
}

▶ Example: Number Guessing Game

TEXT 📖 Display only
import java.util.Scanner;
import java.util.Random;

public class GuessGame {
    public static void main(String[] args) {
        Random random = new Random();
        int target = random.nextInt(100) + 1;
        Scanner scanner = new Scanner(System.in);
        int guess = 0;
        
        System.out.println("Number Guessing Game (1-100)");
        
        while (guess != target) {
            System.out.print("Enter your guess: ");
            guess = scanner.nextInt();
            
            if (guess > target) {
                System.out.println("Too high!");
            } else if (guess < target) {
                System.out.println("Too low!");
            } else {
                System.out.println("Congratulations! You got it!");
            }
        }
        
        scanner.close();
    }
}

3. do-while Loop

The do-while loop executes the loop body at least once.

(1) Syntax

JAVA
do {
    // Loop body
} while (condition);

▶ Example: Menu Loop

TEXT 📖 Display only
import java.util.Scanner;

public class MenuDemo {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int choice;
        
        do {
            System.out.println("\n=== Main Menu ===");
            System.out.println("1. Start Game");
            System.out.println("2. Settings");
            System.out.println("3. Exit");
            System.out.print("Enter your choice: ");
            choice = scanner.nextInt();
            
            switch (choice) {
                case 1:
                    System.out.println("Starting game...");
                    break;
                case 2:
                    System.out.println("Opening settings...");
                    break;
                case 3:
                    System.out.println("Goodbye!");
                    break;
                default:
                    System.out.println("Invalid choice");
            }
        } while (choice != 3);
        
        scanner.close();
    }
}
💡 while vs do-while: while checks the condition first and may never execute. do-while executes first and checks after, guaranteeing at least one execution.


4. for-each Loop

The for-each loop is used to iterate over arrays or collections.

(1) Syntax

JAVA
for (type variable : array or collection) {
    // Use variable
}

▶ Example: Iterating an Array

JAVA
public class ForEachDemo {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        
        // Regular for loop
        for (int i = 0; i < numbers.length; i++) {
            System.out.println(numbers[i]);
        }
        
        // for-each loop
        for (int num : numbers) {
            System.out.println(num);
        }
    }
}
▶ Try it Yourself
💡 When to use: Use for-each when you only need the elements. Use regular for when you need the index.


5. break and continue

(1) break: Exit the Loop

JAVA
public class BreakDemo {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            if (i == 5) {
                break;  // Exit the loop when i equals 5
            }
            System.out.println(i);
        }
        // Output: 1 2 3 4
    }
}

(2) continue: Skip Current Iteration

JAVA
public class ContinueDemo {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            if (i % 2 == 0) {
                continue;  // Skip even numbers
            }
            System.out.println(i);
        }
        // Output: 1 3 5 7 9
    }
}

6. Nested Loops

Loops can be nested inside each other.

▶ Example: Multiplication Table

JAVA
public class MultiplicationTable {
    public static void main(String[] args) {
        for (int i = 1; i <= 9; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(j + " × " + i + " = " + (i * j) + "\t");
            }
            System.out.println();
        }
    }
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
1 × 1 = 1
1 × 2 = 2  2 × 2 = 4
1 × 3 = 3  2 × 3 = 6  3 × 3 = 9
...

▶ Example: Print a Triangle

JAVA
public class TriangleDemo {
    public static void main(String[] args) {
        int rows = 5;
        
        for (int i = 1; i <= rows; i++) {
            // Print spaces
            for (int j = 1; j <= rows - i; j++) {
                System.out.print(" ");
            }
            // Print stars
            for (int k = 1; k <= 2 * i - 1; k++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
    *
   ***
  *****
 *******
*********

7. Infinite Loops

If the loop condition is always true, an infinite loop is created.

JAVA
// Infinite loop example (don't do this)
while (true) {
    System.out.println("Infinite loop");
}

// Correct infinite loop (with exit condition)
while (true) {
    // Read user input
    String input = scanner.nextLine();
    if (input.equals("exit")) {
        break;  // Exit when user types "exit"
    }
}

8. ❓ Frequently Asked Questions

Q How do I choose between for and while?
A Use for when the number of iterations is known. Use while when it's unknown. for is more concise, while is more flexible.
Q What's the difference between break and return?
A break exits the current loop. return exits the entire method.
Q How do I exit multiple nested loops?
A Use labeled break. outer: for(...) { for(...) { break outer; } }

❓ FAQ

Q When should I use while vs for?
A Use for when the iteration count is known; use while when it depends on a condition.
Q What does break and continue do?
A break exits the loop entirely; continue skips the current iteration and proceeds to the next.
Q Can I use labels with break?
A Yes. break label; exits the labeled outer loop, useful for nested loops.

📖 Summary

📝 Exercises

  1. Sum: Calculate the sum of all odd numbers from 1 to 100
  2. Factorial: Calculate 10 factorial (10! = 10 × 9 × ... × 1)
  3. Multiplication table: Use nested loops to print the complete multiplication table

9. Next Lesson

In the next lesson, we'll learn about Arrays — how to store and operate on a group of data.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏