Module 2 of 5 · Java Fundamentals Part 2 · Beginner

Loops: Repeating Code

Duration: 5 min

What are Loops?

Loops allow you to execute a block of code multiple times. Instead of writing the same code over and over, you write it once and tell Java to repeat it. This is essential for processing collections of data and automating repetitive tasks.

The for Loop

The for loop is used when you know exactly how many times you want to repeat code. It has three parts: initialization, condition, and increment.

public class ForLoop {
    public static void main(String[] args) {
        // Print numbers 1 to 5
        for (int i = 1; i <= 5; i++) {
            System.out.println("Number: " + i);
        }
        
        System.out.println();
        
        // Print even numbers from 0 to 10
        for (int i = 0; i <= 10; i += 2) {
            System.out.println(i);
        }
    }
}
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

0
2
4
6
8
10

The while Loop

The while loop repeats code as long as a condition is true. Use it when you don't know in advance how many times you need to repeat.

public class WhileLoop {
    public static void main(String[] args) {
        int count = 1;
        
        while (count <= 5) {
            System.out.println("Count: " + count);
            count++;
        }
        
        System.out.println();
        
        // Countdown
        int countdown = 5;
        while (countdown > 0) {
            System.out.println(countdown);
            countdown--;
        }
        System.out.println("Blastoff!");
    }
}
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

5
4
3
2
1
Blastoff!

The do-while Loop

The do-while loop is similar to while, but it executes the code block at least once before checking the condition. This is useful when you want to guarantee at least one execution.

public class DoWhileLoop {
    public static void main(String[] args) {
        int i = 1;
        
        do {
            System.out.println("i = " + i);
            i++;
        } while (i <= 3);
    }
}
i = 1
i = 2
i = 3

The Enhanced for Loop (for-each)

The enhanced for loop (also called for-each) is used to iterate through arrays and collections. It's simpler than a traditional for loop when you don't need the index.

public class EnhancedForLoop {
    public static void main(String[] args) {
        String[] fruits = {"Apple", "Banana", "Orange", "Mango"};
        
        // Traditional for loop
        System.out.println("Traditional for loop:");
        for (int i = 0; i < fruits.length; i++) {
            System.out.println(fruits[i]);
        }
        
        System.out.println();
        
        // Enhanced for loop
        System.out.println("Enhanced for loop:");
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}
Traditional for loop:
Apple
Banana
Orange
Mango

Enhanced for loop:
Apple
Banana
Orange
Mango

Loop Control: break and continue

• break: Exits the loop immediately
• continue: Skips the current iteration and goes to the next one

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

Using continue:
1
2
4
5

💡 Tip: Be careful with while loops - make sure your condition will eventually become false, or you'll have an infinite loop!

Learn more: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html

❓ Which loop is best when you know exactly how many times you need to repeat?

❓ What is a best practice when working with Loops?

💡 Tip: Pro Tip: Master Loops thoroughly. This foundation is crucial for writing professional Java code.

← Previous Continue interactively → Next →

Related Courses