Java Loops Explained: while, do-while, for, for-each
Java Loop Types: while and for
A loop is a language construct that executes the same fragment of a program multiple times.
Java has four loop statements, and it is convenient to divide them into two types: the "while-type" and the "n-times-type".
The "while-type" repeats an action while a certain condition is true. Example: increase a number by 5 until it becomes three digits. This type includes the while and do-while loops:
while (boolexpr) { /* statements */ }
do { /* statements */ } while (boolexpr);
The "n-times-type" repeats an action a number of times that is known in advance. Example: multiply a number by itself 4 times. This type includes the for and for-each loops:
for (initialization; condition; iteration) { /* statements */ }
for (type variable : arrayOrCollection) { /* statements */ }
The loop's exit condition must be clear to avoid accidentally creating an infinite loop. Let's look at each of these loops in detail.
while Loop
The while loop is a "while-type" loop in Java. It is used when a block of code should execute repeatedly while a specific condition is true and the number of repetitions is not known in advance.
After the keyword while, in parentheses, you specify an expression of type boolean — this is the loop condition. Then, inside curly braces, you write the loop body — the code that will repeat as long as the condition evaluates to true. In the example below, while the condition n > 0 holds, System.out.println is called. The variable n changes inside the loop body — this is what eventually lets the loop terminate.
public class WhileExample1 {
public static void main(String[] args) {
int n = 10;
while (n > 0) {
System.out.println("Tick " + n--);
}
}
} The condition of the while loop is checked before the loop body is executed. If it is false on the very first check, the body never runs at all. This is the main difference between while and do-while.
The next example shows a while loop without a body. Given two numbers, 100 and 200, the goal is to find the midpoint between them. The value of i increases by 1 on each iteration and j decreases until they become equal. The changes to i and j happen inside the condition itself, so no loop body is needed — a semicolon is used instead:
public class NoBodyExample {
public static void main(String[] args) {
int i = 100;
int j = 200; // find midpoint between i and j
while (++i < --j) ; // loop without a body
System.out.println("Midpoint: " + i);
}
} The while loop is also used to create infinite loops with while (true). Such a loop never ends on its own, so it must contain a break statement (or return) inside — otherwise the program hangs:
public class EndlessLoopExample {
public static void main(String[] args) {
int i = 0;
while (true) {
System.out.println(i++);
if (i == 5) {
break; // exit the infinite loop
}
}
}
} do-while Loop
The do-while loop is similar to the while loop — it is also a "while-type" loop with a body and a condition. The key difference is that the condition is written after the body and checked after the body is executed. This means the do-while body executes at least once, even if the condition evaluates to false right away.
Example of a do-while loop:
public class DoWhileExample {
public static void main(String[] args) {
int n = 10;
do {
System.out.println("Tick " + n--);
} while (n > 0);
}
} A classic use case for do-while is asking the user for input: the value has to be read at least once, and then the prompt repeats until the user enters a valid value.
for Loop
The for loop in Java is used when you need to execute a block of code multiple times and the number of repetitions is known in advance.
General syntax of the for loop:
for (initialization; condition; iteration) { /* statements */ } Example of a for loop:
public class ForTickExample {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println("Tick " + i);
}
}
} The first section (initialization) usually declares a variable that counts the loop's repetitions. It is called the loop counter and is most often named i. The counter is given a starting value.
The second section (condition) sets the limit on the counter — it defines how long the loop keeps running based on the counter's value.
The third section (iteration) contains an expression that updates the counter after each pass of the loop. This is typically an increment or decrement, but any expression that assigns a new value to the counter works. Modifying the counter inside the loop body is not recommended — such code is harder to read and easier to break.
Before each pass of the loop (but after the initialization), the condition is checked. If it is true, the next iteration of the body executes. Just like with while, the body may not execute at all if the condition is false on the first check.
In the first and third sections, you can list several variables and expressions separated by commas:
public class ForExample {
public static void main(String[] args) {
for (int i = 1, j = 4; i < j; i++, j--) {
System.out.println("i = " + i);
System.out.println("j = " + j);
}
}
} All three sections of the for loop are optional. If you omit all of them, you get another form of an infinite loop: for (;;) { }.
for-each Loop
The for-each loop (often written as foreach or "for each"; its official name is the enhanced for loop) is a variation of the for loop introduced in Java 5. It is used to iterate sequentially over the elements of arrays and collections (any objects that implement the Iterable interface). Its notation is shorter and safer than a regular for loop: you cannot make an off-by-one mistake with index boundaries.
General syntax of the for-each loop:
for (type variable : arrayOrCollection) { /* statements */ } In the following example, on each iteration the variable number is automatically assigned the value of the next element of the numbers array, from the first element to the last:
public class ForEachExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println("Number: " + number);
}
}
} If you simply need to visit every element of an array or a collection, choose for-each — the code comes out shorter and clearer.
Keep in mind
A for-each loop gives you no access to the element's index, and assigning a new value to the iteration variable does not change the array or collection itself. If you need to know an element's position, replace elements, or traverse only part of an array — use a regular for loop with a counter.
break and continue Statements
Any loop can be controlled with two statements:
break— terminates the loop immediately; execution continues with the line after the loop;continue— skips only the current iteration and jumps to the next condition check.
public class BreakContinueExample {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue; // skip even numbers
}
if (i > 7) {
break; // leave the loop entirely
}
System.out.println(i); // prints 1, 3, 5, 7
}
}
} In nested loops, break and continue affect only the loop they are directly placed in. To exit several levels at once, Java provides labeled statements (labeled break).
Which Loop to Choose
| Loop | When to use | Condition check | Minimum iterations |
|---|---|---|---|
| while | The number of repetitions is not known in advance | Before the body | 0 |
| do-while | The body must run at least once (e.g., prompting for input) | After the body | 1 |
| for | The number of repetitions is known; you need a counter or an index | Before the body | 0 |
| for-each | Visiting every element of an array or a collection | While elements remain | 0 |
Frequently Asked Questions
What is the difference between while and do-while in Java?
while checks its condition before executing the body, so the body may never run. do-while checks the condition after the body, so the body is guaranteed to execute at least once, even if the condition is false right away.
When should I use for and when for-each (foreach)?
for-each fits when you simply need to visit every element of an array or a collection. A regular for loop is needed when the element's index matters, when you have to modify array elements, use a non-standard step, or traverse only part of the elements.
How do I create an infinite loop in Java?
Two standard ways: while (true) { } and for (;;) { }. To keep the program from hanging, such a loop must contain an exit — a break or return statement that fires under a certain condition.
Can I modify array elements inside a for-each loop?
No. The iteration variable is a copy of the element's value (or a copy of the reference), so assigning a new value to it does not change the array. To replace elements, use a regular for loop and access elements by index.
Comments