JAVA • Beginner

Java Loops

Loops let you repeat a block of code multiple times. Java provides 4 types of loops — for, while, do-while, and the enhanced for-each. Choosing the right loop makes your code cleaner and faster.

1. for Loop

Used when the number of iterations is known in advance.

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

// Output: 1 2 3 4 5

Structure

for (initialization; condition; update) {
    // body
}
  • initialization — runs once at the start
  • condition — checked before each iteration
  • update — runs after each iteration

Counting Backwards

for (int i = 10; i >= 1; i--) {
    System.out.println(i);
}

Step by 2

for (int i = 0; i <= 10; i += 2) {
    System.out.println(i);   // 0 2 4 6 8 10
}

2. while Loop

Used when the number of iterations is unknown — depends on a condition.

int i = 1;

while (i <= 5) {
    System.out.println(i);
    i++;
}
⚠ Infinite Loop Warning

If the condition never becomes false, the loop runs forever. Always ensure your loop variable changes inside the loop body. Example of BAD code: while (i <= 5) { System.out.println(i); } — i never increments.

3. do-while Loop

Like while, but the body runs at least once even if the condition is false.

int i = 10;

do {
    System.out.println(i);
    i++;
} while (i <= 5);

// Output: 10 (runs once, then condition fails)

When to Use do-while?

  • Menu-driven programs (show menu at least once)
  • Input validation (ask user at least once)
  • Any case where you want the body to run before checking the condition

4. Enhanced for-each Loop

Perfect for iterating through arrays and collections without managing an index.

int[] numbers = {10, 20, 30, 40, 50};

for (int num : numbers) {
    System.out.println(num);
}

// String array
String[] fruits = {"apple", "banana", "mango"};
for (String fruit : fruits) {
    System.out.println(fruit);
}

for vs for-each

// Classic for — with index
for (int i = 0; i < fruits.length; i++) {
    System.out.println(i + ": " + fruits[i]);
}

// for-each — simpler, no index
for (String fruit : fruits) {
    System.out.println(fruit);
}

Use for-each when you don't need the index. Use classic for when you need to modify the array or track index positions.

break Statement — Exit Loop

Immediately terminates the loop.

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

// Output: 1 2 3 4

continue Statement — Skip Current Iteration

Skips the rest of the current iteration and moves to the next.

for (int i = 1; i <= 10; i++) {
    if (i % 2 == 0) {
        continue;
    }
    System.out.println(i);
}

// Output: 1 3 5 7 9 (only odd numbers)

Nested Loops

A loop inside another loop. Commonly used for patterns, matrices, tables.

// Multiplication table 1-3
for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
        System.out.println(i + " x " + j + " = " + (i * j));
    }
    System.out.println("---");
}

Star Pattern (Triangle)

int rows = 5;

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

// Output:
// *
// * *
// * * *
// * * * *
// * * * * *

Number Pyramid

int n = 5;

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

// Output:
// 1
// 1 2
// 1 2 3
// 1 2 3 4
// 1 2 3 4 5

Labeled break and continue

Java allows labels to break out of nested loops.

outer:
for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
        if (i == 2 && j == 2) {
            break outer;   // Breaks out of BOTH loops
        }
        System.out.println(i + ", " + j);
    }
}

Real Example — Sum and Average

public class Calculate {
    public static void main(String[] args) {
        int[] marks = {85, 92, 78, 88, 95};

        int sum = 0;

        // Sum using for-each
        for (int mark : marks) {
            sum += mark;
        }

        double average = (double) sum / marks.length;

        System.out.println("Total: " + sum);
        System.out.println("Average: " + average);
        System.out.printf("Average (2 decimals): %.2f%n", average);
    }
}

Infinite Loop (Intentional)

while (true) {
    // Runs forever until break is called
    // Use in menu systems, servers, game loops
}

Loop Comparison

Loop Type      When to Use
---------      -----------
for            Known count / fixed iterations
while          Unknown count / condition-based
do-while       Body must run at least once
for-each       Iterating arrays/collections
💡 Academy Tip

for-each is preferred when you don't need the index. It's cleaner and avoids off-by-one errors. Use classic for when you need the index or to modify the collection.

📝 Try Yourself

1. Print numbers from 1 to 100 using a for loop.
2. Print the multiplication table of 7.
3. Find the sum of all even numbers from 1 to 50.
4. Print a right-angled triangle pattern of stars (5 rows).
5. Use do-while to print numbers from 1 to 5.
6. Iterate over an array of 5 fruits using for-each.

Quick Revision

  • for — known iteration count.
  • while — condition-based, may run 0 times.
  • do-while — runs at least once.
  • for-each — iterating arrays/collections.
  • break — exit the loop entirely.
  • continue — skip the current iteration.
  • Labels allow breaking out of nested loops.
  • Watch out for infinite loops — always update the loop variable.

Interview Questions

Q: Difference between while and do-while?

A: while checks the condition BEFORE running the body — may run 0 times. do-while checks the condition AFTER — runs at least once.

Q: Difference between break and continue?

A: break exits the entire loop immediately. continue skips the rest of the current iteration and moves to the next one.

Q: When should you use for-each instead of classic for?

A: Use for-each when you only need to read each element and don't care about the index. Use classic for when you need the index, need to modify elements, or need to iterate in a non-sequential way.

Q: Can you modify an array inside a for-each loop?

A: You can modify the elements (e.g., arr[i] = 5 won't work with for-each) but the loop variable is a copy. You can't change the array reference, but you can modify object contents if it's an object array. For primitive arrays, use classic for to modify.

Q: What is a labeled loop?

A: A loop with a name (label) that allows break or continue to target a specific outer loop in nested loops. Example: outer: for(...) { for(...) { break outer; } }.

Q: Difference between System.out.print() and System.out.println()?

A: print() outputs without a newline. println() outputs WITH a newline. Useful for printing patterns on the same line.

Want to Master Java?

Join our Java course in Varanasi — practical classes and career support at our Sarnath centre.

Ask on WhatsApp
Chat with us