Loops in Java — For While Do-While Tutorial
Chapter 04 · Java Programming Series
PBA Institute 13 min read Beginner 2024

Loops in Java

Loops let a program execute a block of code multiple times without rewriting it. Java offers three main loops — for, while and do-while — plus an enhanced for-each loop for arrays and collections. Loops form the backbone of algorithms ranging from simple counting to complex data processing.

Key Features

🔁

For Loop

Best when you know the number of iterations in advance.

🔄

While Loop

Repeats while a condition is true — useful when count is unknown.

⏭️

Do-While

Executes at least once before checking the condition.

📚

For-Each

Compact iteration over arrays and collections.

⏸️

Break

Terminates the loop immediately.

Continue

Skips the current iteration and continues with the next.

Syntax

  • for (init; condition; update) { /* body */ }
  • while (condition) { /* body */ }
  • do { /* body */ } while (condition);
  • Use break to exit early, continue to skip an iteration.

Loop Comparison

LoopWhen to UseCheckGuaranteed Run
forKnown countBeforeNo
whileUnknown countBeforeNo
do-whileMenu / RetryAfterYes (1×)
for-eachArray / CollectionPer element

Detailed Explanation & First Example

Let's start with a hands-on example. The program below shows the core idea behind Loops in just a few lines of Java. Read it line by line and observe how Java executes each statement in order.

Print 1 to 5 with For Loop
class Main
{
    public static void main(String args[])
    {
        for (int i = 1; i <= 5; i++)
        {
            System.out.println("Count: " + i);
        }
    }
}
Output Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

Examples — Beginner to Advanced

The following examples progress from simple to more practical patterns. Try each in your IDE, change the inputs and observe the output. This is the fastest way to internalize the concept.

Sum of First N Numbers
class Main
{
    public static void main(String args[])
    {
        int n = 10, sum = 0;

        for (int i = 1; i <= n; i++)
            sum += i;

        System.out.println("Sum = " + sum);
    }
}
Output Sum = 55
Multiplication Table — While
class Main
{
    public static void main(String args[])
    {
        int n = 5, i = 1;

        while (i <= 10)
        {
            System.out.println(n + " x " + i + " = " + (n * i));
            i++;
        }
    }
}
Output 5 x 1 = 5
5 x 2 = 10
... up to 5 x 10 = 50
Do-While Menu
class Main
{
    public static void main(String args[])
    {
        int count = 0;

        do {
            System.out.println("Run " + count);
            count++;
        } while (count < 3);
    }
}
Output Run 0
Run 1
Run 2
Break Example
class Main
{
    public static void main(String args[])
    {
        for (int i = 1; i <= 10; i++)
        {
            if (i == 5) break;
            System.out.println(i);
        }
    }
}
Output 1
2
3
4
Continue Example
class Main
{
    public static void main(String args[])
    {
        for (int i = 1; i <= 6; i++)
        {
            if (i % 2 == 0) continue;
            System.out.println(i);
        }
    }
}
Output 1
3
5
For-Each Loop
class Main
{
    public static void main(String args[])
    {
        int arr[] = {10, 20, 30, 40};

        for (int x : arr)
            System.out.println(x);
    }
}
Output 10
20
30
40

Notes & Tips

  • An infinite loop happens when the condition never becomes false — use for(;;) or while(true) intentionally only.
  • Always update the loop variable to avoid infinite loops.
  • Use for-each when you don't need the index.
  • Avoid changing a collection while iterating over it — use Iterator.remove().
  • break only exits the innermost loop. Use labeled break to exit outer loops.

Real-World Use Cases

Data Processing

Iterate over arrays or lists to compute totals, averages and reports.

Game Loops

The main game loop continuously updates state and renders graphics.

Searching

Linear search uses a loop to scan an array element by element.

Batch Tasks

Process emails, files or records one by one in a loop.

Practice Questions

Reading is not enough — practice solidifies knowledge. Try every question below in your own editor before peeking at any solution.

  • Q1. Print all even numbers from 1 to 50.
  • Q2. Find the factorial of a number using a for loop.
  • Q3. Reverse a number using a while loop.
  • Q4. Count the digits of a positive integer.
  • Q5. Print the Fibonacci series up to 20 terms.

Interview Questions

These are the most common questions asked in Java interviews on this topic. Memorize the concept, not just the answer — interviewers often follow up with edge cases.

Q1 Difference between while and do-while?
while checks the condition first; do-while runs the body once and then checks, guaranteeing at least one execution.
Q2 Which loop is best for iterating an array?
The for-each loop when you don't need the index; otherwise use a classic for loop.
Q3 What is an infinite loop?
A loop whose condition never evaluates to false. Useful in server loops but a bug otherwise.
Q4 Difference between break and continue?
break exits the loop entirely; continue skips to the next iteration.
Q5 Can we use a labeled break in Java?
Yes — label a loop with name: and use break name; to exit it from a nested loop.

FAQ

FAQ 1 Which Java loop is fastest?
Performance is nearly identical for for, while and do-while. Choose based on clarity, not speed.
FAQ 2 Can I declare multiple variables in a for loop?
Yes — for (int i=0, j=10; i<j; i++,j--) is valid.
FAQ 3 How do you exit a nested loop?
Use a labeled break: outer: for(...) { for(...) { break outer; } }.
FAQ 4 What is a do-while loop used for?
Menus, user retries, and any scenario where the body must run at least once before deciding to repeat.
FAQ 5 Why prefer the for-each loop?
It is shorter, less error-prone, and avoids off-by-one index bugs.

Common Mistakes to Avoid

Even experienced developers slip on the same pitfalls. Watch out for these classic mistakes while working with Loops in Java:

  • Forgetting the semicolon ; at the end of statements while using Loops.
  • Mixing up similar method names — read Java docs before using new APIs related to Loops.
  • Ignoring compiler warnings — they often hint at bugs that will appear later in production.
  • Hard-coding values that should come from configuration files or environment variables.
  • Not handling edge cases: empty inputs, very large inputs, negative numbers and null references.
  • Skipping unit tests — small tests prevent big regressions, especially around control flow.

At-a-Glance

Advantages
Readable Reusable Testable Standardized
Watch Out
Edge Cases Null Safety Performance Memory
Java Version
JDK 8+ JDK 11 JDK 17 LTS JDK 21 LTS
Pair With
If Else For Loop OOP Best Practices

Best Practices

📐

Follow Conventions

Use camelCase for variables, PascalCase for classes, UPPER_SNAKE for constants.

🧪

Write Tests

Cover happy path and edge cases with JUnit before shipping changes to production.

🧹

Keep Methods Short

A method should do one thing and fit on a single screen. Refactor when it grows.

🔍

Validate Inputs

Never trust user input. Validate at the boundary, fail fast and log meaningfully.

📝

Comment the Why

Comments should explain why a decision was made — not what the code does line by line.

♻️

Refactor Often

Small frequent refactors are cheap and safe; big rewrites are risky and expensive.

Pro Tips

TIP 01 Use clear, descriptive identifiers when writing code involving Loops — your future self will thank you.
TIP 02 Run small experiments in jshell (Java's REPL) to test ideas before committing them to a project.
TIP 03 Read the official java.lang and java.util documentation. The standard library is huge and surprisingly powerful.
TIP 04 Combine this topic with unit testing (JUnit 5) — it forces you to think about edge cases.
TIP 05 Practice with online judges (HackerRank, LeetCode) to internalise the patterns used in real interviews.

Quick Reference

Keyword / ConceptMeaningUsed ForJava Since
LoopsLoops conceptCore Java1.0
classBlueprint of objectsOOP1.0
staticClass-level memberUtilities1.0
finalConstant / no overrideImmutability1.0
publicAccessible everywhereAPI exposure1.0
privateClass-only accessEncapsulation1.0

Related Topics

PREV If Else — strengthens your understanding of the previous building block.
NEXT For Loop — the natural progression after mastering Loops.
OOP Object Oriented Programming — Class, Object, Inheritance, Polymorphism, Encapsulation, Abstraction.
DSA Data Structures & Algorithms — apply this topic in real coding-interview challenges.
STD LIB Java Standard Library — explore java.util, java.lang and java.io.

Summary

Loops are the foundation of repetition in Java. Use for when iterations are known, while when they are not, do-while for guaranteed first runs, and for-each for cleaner array iteration. Master break and continue to control loop flow precisely.

Continue Learning