JavaBasicsbeginner
Updated:

Java Loops: for, while, do-while and for-each

7 min read

Every Java loop explained with runnable code: for, while, do-while and for-each, when to use each one, and how break and continue change the flow.

TL;DR – Quick Answer

Java has four loops: for (known number of iterations), while (repeat while a condition holds), do-while (like while, but the body always runs at least once) and the enhanced for-each loop for walking through arrays and collections. break exits a loop early and continue skips to the next iteration.

On This Page

Loops are how Java repeats work: processing every order in a list, retrying a failed network call, printing the star patterns that show up in nearly every fresher coding round. Java gives you four loop constructs, and each exists because it fits a different shape of problem. Pick the right one and your code almost writes itself; pick the wrong one and you end up managing indexes and flags you never needed.

If you have not yet covered how conditions work, read Java control statements first — every loop is driven by a boolean condition, just like if.

The four loops at a glance

Loop Condition checked Best when
for Before each iteration You know how many times to repeat
while Before each iteration You repeat until something changes
do-while After each iteration The body must run at least once
for-each N/A (iterator-driven) You visit every element of an array/collection

All four can be exited early with break and can skip an iteration with continue.

The for loop

The classic for loop packs initialization, condition and update into one line:

public class SumOfN {
    public static void main(String[] args) {
        int n = 10;
        int sum = 0;

        for (int i = 1; i <= n; i++) {
            sum += i;
        }
        System.out.println("Sum of 1 to " + n + " = " + sum);  // 55
    }
}

Execution order matters and interviewers test it: int i = 1 runs once; then the condition i <= n is checked; if true, the body runs; then the update i++ runs; then back to the condition. When i reaches 11 the condition fails and the loop ends. The variable i exists only inside the loop — that tight scope is a feature, not a limitation.

The increment i++ is one of several Java operators you can use in the update section: i += 2 steps by two, i-- counts down.

Common mistake: A common mistake beginners make is the off-by-one error: writing i < n when they meant i <= n, or starting at 1 when the data starts at 0. Before you run any loop, trace the first iteration and the last iteration by hand. Those two are where off-by-one bugs live.

The while loop

Use while when you cannot predict the number of iterations — you loop as long as a condition holds:

public class DigitCounter {
    public static void main(String[] args) {
        int number = 48205;
        int digits = 0;

        while (number != 0) {
            number = number / 10;   // drop the last digit
            digits++;
        }
        System.out.println("Digit count: " + digits);  // 5
    }
}

Each pass integer-divides the number by 10: 48205 → 4820 → 482 → 48 → 4 → 0. You could not easily write this as a counted for loop because the iteration count depends on the input. Reversing a number, computing a GCD, reading input until a sentinel value — these are all natural while problems.

The danger with while is forgetting to change the condition variable inside the body. If number were never divided, the loop would spin forever.

The do-while loop

do-while moves the condition check to the end, guaranteeing the body executes at least once:

int choice;
do {
    System.out.println("1. Deposit  2. Withdraw  3. Exit");
    choice = scanner.nextInt();
    // handle the choice...
} while (choice != 3);

This is the menu-driven-program pattern: you must display the menu before you can know whether the user wants to continue. In practice do-while is the rarest of the four loops, but it is a favourite viva question precisely because the difference from while is subtle.

The for-each loop

The enhanced for loop (Java 5+) iterates over arrays and collections without an index:

public class MarksAverage {
    public static void main(String[] args) {
        int[] marks = {72, 85, 64, 91, 78};
        int total = 0;

        for (int m : marks) {
            total += m;
        }
        System.out.println("Average: " + (double) total / marks.length);  // 78.0
    }
}

Read for (int m : marks) as "for each m in marks". There is no index to initialise, no condition to get wrong, no chance of an ArrayIndexOutOfBoundsException. The same syntax works on any collection, such as an ArrayList.

Its limits: you cannot get the current position, you cannot iterate in reverse and assigning to the loop variable (m = 0;) changes only the local copy, not the array element. When you need any of those, fall back to the classic for.

Pro tip: Default to for-each for read-only traversal and switch to an indexed for only when you actually need the index. Less state means fewer bugs, and the intent of the code becomes obvious to whoever reads it next. Once you learn Java Streams, you will see the same principle taken further.

break, continue and nested loops

break exits the loop immediately; continue abandons the current iteration and jumps to the next condition check:

int[] numbers = {4, 9, 15, 22, 7, 30};
for (int n : numbers) {
    if (n % 2 != 0) {
        continue;            // skip odd numbers
    }
    if (n > 25) {
        break;               // stop entirely at the first number over 25
    }
    System.out.println(n);   // prints 4, then 22
}

Trace it: 4 prints; 9 and 15 are skipped by continue; 22 prints; 7 is skipped; 30 triggers break before printing. Note that 30 itself is not printed — break fires before the print statement.

Used sparingly, both keywords keep loops flat and readable. A loop peppered with five continues usually means the filtering logic belongs in an if around the body instead.

Nested loops and labels

A loop inside a loop multiplies iterations: an outer loop of 4 passes around an inner loop of 4 passes runs the inner body 16 times. Pattern printing is the classic drill:

for (int row = 1; row <= 4; row++) {
    for (int col = 1; col <= row; col++) {
        System.out.print("* ");
    }
    System.out.println();
}
// *
// * *
// * * *
// * * * *

Inside nested loops, break and continue affect only the innermost loop. To break out of both, label the outer loop and break to the label:

outer:
for (int i = 0; i < matrix.length; i++) {
    for (int j = 0; j < matrix[i].length; j++) {
        if (matrix[i][j] == target) {
            System.out.println("Found at " + i + "," + j);
            break outer;
        }
    }
}

Interview note: Nested-loop questions rarely stop at the pattern. The follow-up is usually about cost: two nested loops over n elements do n × n iterations, which is O(n²). If you can explain why a nested search over 10,000 records means up to 100 million comparisons, you have answered the real question behind the pattern drill.

Infinite loops: bug or feature

while (true) and for (;;) never terminate on their own. That is a bug when you forgot i++, but a deliberate design in servers, game loops and consumers that wait for messages and exit via break or return on a shutdown signal.

When a program hangs, check three things in this order: does the loop variable actually change inside the body, does it change in the direction that ends the loop, and can the condition ever become false for the given input? Nine out of ten frozen fresher programs fail one of those three checks.

Loop patterns interviewers expect you to know

Beyond syntax, a handful of loop patterns cover the majority of fresher screening questions, and each maps cleanly onto one loop type.

The accumulator pattern initialises a result before the loop and updates it inside — summing marks, building a product, concatenating output. The counter pattern increments only when a condition matches, which answers every "how many elements are even/positive/ above average" question. The search pattern walks the data and uses break the moment the target is found, so you never waste iterations after success. The min-max pattern seeds a best-so-far with the first element and challenges it on every pass.

Two habits make these patterns reliable. Initialise the accumulator correctly: 0 for sums, 1 for products, the first element (never 0) for a maximum, because an all-negative array breaks the zero-seeded version. And keep the update in exactly one place — loops where the variable changes in three different branches are where infinite loops and skipped elements hide.

If you can write each of these four patterns from a blank editor in under two minutes, you are ready for the loop section of any entry-level test.

Choosing the right loop

A quick decision guide you can apply in interviews and assignments:

  • Known count or index needed → for
  • Repeat until a condition changes, count unknown → while
  • Body must run at least once (menus, retry prompts) → do-while
  • Visit every element, no index needed → for-each

Loops plus arrays are the backbone of fresher coding tests — reversing arrays, finding maximums, counting frequencies. Practise those combinations until they are automatic. In the Java Full Stack course at CodeBegun we spend a full week on loop-and-array drills before touching OOP, because everything that comes later — collections, streams, algorithms — assumes this layer is solid.

Frequently Asked Questions

What are the four types of loops in Java?
Java provides the classic for loop, the while loop, the do-while loop and the enhanced for-each loop. The first three are condition-driven, while for-each is designed specifically to iterate over arrays and collections without managing an index.
What is the difference between while and do-while in Java?
A while loop checks its condition before running the body, so the body may never execute. A do-while loop checks the condition after the body, so the body always runs at least once. do-while suits menu-driven programs where you must show the menu before asking whether to repeat.
What is the difference between break and continue?
break terminates the entire loop immediately and control moves to the first statement after the loop. continue only skips the rest of the current iteration and jumps to the next condition check. In nested loops, both affect only the innermost loop unless you use a label.
Can a for loop run forever in Java?
Yes. Writing for(;;) or while(true) creates an infinite loop, which is intentional in servers and event loops that wait for work. Accidental infinite loops usually come from forgetting to update the loop variable or updating it in the wrong direction.
When should I use for-each instead of a for loop?
Use for-each whenever you only need to read every element of an array or collection, because there is no index to get wrong. Use the classic for loop when you need the index, want to modify elements by position, iterate in reverse or skip elements by a step.
Why does modifying a list inside a for-each loop throw an exception?
The for-each loop uses an iterator behind the scenes. If you call add or remove on the collection directly during iteration, the iterator detects the structural change and throws ConcurrentModificationException. Use an explicit Iterator with its remove method, or removeIf, instead.

Want to Build Your Career in Java Full Stack with AI?

Join CodeBegun and train with working industry engineers — Explore the Program

Apply for Demo Class →
Siva Prasad Galaba
Founder, CodeBegun · Staff Engineer

Founder of CodeBegun. 15+ years building Java systems at companies like Crunchyroll. Teaches Java, Spring Boot and system design the way the industry actually works, and mentors students through projects, mock interviews and placement preparation.

Technically reviewed by CodeBegun Technical TeamLast reviewed 14 July 2026 LinkedIn
Chat with us