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
| Loop | When to Use | Check | Guaranteed Run |
|---|---|---|---|
| for | Known count | Before | No |
| while | Unknown count | Before | No |
| do-while | Menu / Retry | After | Yes (1×) |
| for-each | Array / Collection | — | Per 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.
class Main
{
public static void main(String args[])
{
for (int i = 1; i <= 5; i++)
{
System.out.println("Count: " + i);
}
}
}
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.
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);
}
}
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++;
}
}
}
5 x 2 = 10
... up to 5 x 10 = 50
class Main
{
public static void main(String args[])
{
int count = 0;
do {
System.out.println("Run " + count);
count++;
} while (count < 3);
}
}
Run 1
Run 2
class Main
{
public static void main(String args[])
{
for (int i = 1; i <= 10; i++)
{
if (i == 5) break;
System.out.println(i);
}
}
}
2
3
4
class Main
{
public static void main(String args[])
{
for (int i = 1; i <= 6; i++)
{
if (i % 2 == 0) continue;
System.out.println(i);
}
}
}
3
5
class Main
{
public static void main(String args[])
{
int arr[] = {10, 20, 30, 40};
for (int x : arr)
System.out.println(x);
}
}
20
30
40
Notes & Tips
- An infinite loop happens when the condition never becomes false — use
for(;;)orwhile(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.
while checks the condition first; do-while runs the body once and then checks, guaranteeing at least one execution.
The for-each loop when you don't need the index; otherwise use a classic for loop.
A loop whose condition never evaluates to false. Useful in server loops but a bug otherwise.
break exits the loop entirely; continue skips to the next iteration.
Yes — label a loop with
name: and use break name; to exit it from a nested loop.
FAQ
Performance is nearly identical for
for, while and do-while. Choose based on clarity, not speed.
Yes —
for (int i=0, j=10; i<j; i++,j--) is valid.
Use a labeled break:
outer: for(...) { for(...) { break outer; } }.
Menus, user retries, and any scenario where the body must run at least once before deciding to repeat.
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
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
Quick Reference
| Keyword / Concept | Meaning | Used For | Java Since |
|---|---|---|---|
| Loops | Loops concept | Core Java | 1.0 |
| class | Blueprint of objects | OOP | 1.0 |
| static | Class-level member | Utilities | 1.0 |
| final | Constant / no override | Immutability | 1.0 |
| public | Accessible everywhere | API exposure | 1.0 |
| private | Class-only access | Encapsulation | 1.0 |
Related Topics
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.