Java tutorials  /  Java Loops (for, while, do-while)
Chapter 6 · Java

Java Loops (for, while, do-while)

A loop in Java is a control flow structure that repeatedly executes a block of code as long as a specified condition remains true. Java provides four main looping constructs: the 'for' loop, the 'while' loop, the 'do-while' loop, and the enhanced 'for-each' loop, each suited to different repetition scenarios.

Imagine you need to water 50 plants in a garden. Instead of writing out the instruction 'water the plant' 50 separate times, you'd rather say 'repeat this action 50 times' — that's exactly what a loop does in code. A 'for' loop is like counting plants as you go ('do this for plant 1, plant 2, ... up to plant 50'), while a 'while' loop is like continuing to water plants 'as long as there are still unwatered plants left', checking the condition before each attempt.

Consider a payroll system that needs to calculate and print salary slips for every employee in a company database. A 'for' loop (or enhanced for-each loop) would iterate through the entire list of employees exactly once each, applying the same salary calculation logic to each one. Meanwhile, a 'while' loop is commonly used in real applications for tasks like reading data from a file or network stream 'while there is still more data available', since the total number of iterations isn't known in advance — it depends entirely on when the data runs out.

Without loops, repeating any action multiple times would require manually duplicating code for each repetition, which becomes impractical or impossible when dealing with large or variable amounts of data (like processing thousands of database records or user inputs of unknown length). Loops allow programs to process collections of data, repeat calculations, and automate repetitive tasks efficiently, forming one of the most fundamental building blocks of programmatic automation.

  • for Loop: Used when the number of iterations is known or countable in advance. It combines initialization, condition-checking, and increment/decrement into a single compact statement.
  • while Loop: Checks the condition before executing the loop body each time (entry-controlled loop). Used when the number of iterations is not known in advance and depends on a dynamic condition.
  • do-while Loop: Similar to the while loop, but checks the condition after executing the loop body (exit-controlled loop), guaranteeing the loop body executes at least once regardless of the initial condition.
  • Enhanced for-each Loop: A simplified loop specifically designed for iterating over arrays and collections (like ArrayList), automatically handling the indexing/iteration details internally without needing a counter variable.
// for loop: for (initialization; condition; update) { // code block } // while loop: while (condition) { // code block } // do-while loop: do { // code block } while (condition); // enhanced for-each loop: for (dataType item : collectionOrArray) { // code block }
A beginner wants to print all numbers from 1 to 5, calculate the sum of the first 5 natural numbers, and also iterate through an array of names to print a greeting for each — three common repetition scenarios that call for different loop types.
Basic for Loop: Printing Numbers 1 to 5
This example demonstrates the classic for loop structure to print numbers from 1 to 5, showing initialization, condition, and increment all in one line.
Java
public class ForLoopDemo { public static void main(String[] args) { for (int i = 1; i <= 5; i++) { System.out.println("Number: " + i); } } }
Number: 1 Number: 2 Number: 3 Number: 4 Number: 5
'int i = 1' initializes the loop counter once, before the loop starts. 'i <= 5' is checked before every iteration; the loop continues only while this is true. 'i++' executes after each iteration's body completes, incrementing the counter. Once 'i' becomes 6, the condition 'i <= 5' becomes false, and the loop terminates.
do-while Loop: Guaranteed Single Execution
This example demonstrates a do-while loop simulating a simple menu system, showing that the loop body executes at least once even before the condition is first checked.
Java
public class DoWhileDemo { public static void main(String[] args) { int attempts = 0; int maxAttempts = 3; do { attempts++; System.out.println("Attempt number: " + attempts); } while (attempts < maxAttempts); System.out.println("Total attempts made: " + attempts); } }
Attempt number: 1 Attempt number: 2 Attempt number: 3 Total attempts made: 3
Unlike a regular while loop, the do-while loop executes the body first ('attempts++' and the println) and only afterward checks 'attempts < maxAttempts'. This structure guarantees at least one execution of the loop body, which is why do-while is commonly used for scenarios like displaying a menu at least once before checking if the user wants to continue.
Enhanced for-each Loop with an Array
This example uses the simplified for-each loop syntax to iterate through an array of names and print a personalized greeting for each one, without needing a manual index counter.
Java
public class ForEachDemo { public static void main(String[] args) { String[] names = {"Alice", "Bob", "Charlie"}; for (String name : names) { System.out.println("Hello, " + name + "!"); } } }
Hello, Alice! Hello, Bob! Hello, Charlie!
The for-each loop reads as 'for each String named name in the names array'. Java automatically handles the internal iteration and indexing, directly giving access to each element's value ('name') without requiring the programmer to manage an index variable like 'i' or perform manual bounds-checking against the array's length.
  • Creating an Infinite Loop by Forgetting to Update the Counter: Writing a while loop like 'while (i < 10) { System.out.println(i); }' without incrementing 'i' anywhere inside the loop body causes the condition to remain true forever, resulting in an infinite loop that either hangs the program or eventually crashes it with a StackOverflowError or by exhausting system resources.
  • Off-by-One Errors in Loop Conditions: Using '<=' when '<' was intended (or vice versa) is a very common source of bugs, such as writing 'for (int i = 0; i <= array.length; i++)' when iterating through an array — since valid indices only go up to 'array.length - 1', this causes an ArrayIndexOutOfBoundsException on the final iteration when 'i' equals 'array.length'.
  • Attempting to Modify a Collection While Iterating with for-each: Directly adding or removing elements from an ArrayList while iterating over it using a for-each loop throws a 'ConcurrentModificationException' at runtime. To safely remove elements during iteration, an 'Iterator' with its own 'remove()' method, or a standard indexed for loop iterating in reverse, should be used instead.
  • Using a for-each Loop When the Index is Needed: Beginners sometimes try to use a for-each loop when they actually need to know the current index (e.g., to print 'Item #1', 'Item #2'), not realizing the for-each loop doesn't expose an index variable at all. In such cases, a traditional indexed for loop ('for (int i = 0; i < array.length; i++)') is the correct and necessary choice instead.
  • Prefer for-each for Simple Collection Iteration: When you only need to access each element's value (not its index) while iterating over an array or collection, use the enhanced for-each loop. It is more concise, readable, and eliminates the risk of off-by-one indexing errors entirely.
  • Use while Loops for Unknown Iteration Counts: Reserve 'while' loops for situations where the number of iterations genuinely isn't known in advance (like reading from a stream until it ends, or validating user input until it's correct), rather than forcing a 'for' loop with a manually maintained counter variable into that role.
  • Always Double-Check Loop Boundary Conditions: When writing loop conditions involving array or list lengths, deliberately pause and verify whether '<' or '<=' is correct for your specific starting index and use case, since off-by-one errors are among the most common and easily overlooked bugs in loop-based code.
  • Avoid Modifying Loop Control Variables Inside the Loop Body: Manually changing the value of a for loop's counter variable (e.g., 'i') inside the loop's body, in addition to the automatic update in the for statement itself, makes the loop's termination behavior extremely difficult to reason about and predict. Keep counter modification confined strictly to the loop's own update expression.
What is the key difference between a while loop and a do-while loop in Java?
A 'while' loop is entry-controlled, meaning it checks its condition before executing the loop body each time; if the condition is false on the very first check, the loop body never executes at all. A 'do-while' loop is exit-controlled, meaning it executes the loop body first, and only checks the condition afterward, at the end of each iteration. This guarantees that a do-while loop's body always executes at least once, regardless of whether the condition is true or false initially, which makes it particularly useful for scenarios like input validation or menu systems where at least one execution is always required.
Why can't you directly remove an element from an ArrayList while iterating over it using a for-each loop, and what is the correct way to do it?
Internally, a for-each loop over a Collection uses an Iterator, which maintains an internal modification counter to track changes to the underlying collection. If the list is structurally modified (elements added or removed) directly through the list's own methods (like 'list.remove()') during iteration, the iterator detects this mismatch on its next access attempt and throws a 'ConcurrentModificationException' to prevent unpredictable behavior. The correct way to safely remove elements during iteration is to use the Iterator's own 'remove()' method directly (e.g., 'iterator.remove()'), which properly updates the iterator's internal state, or alternatively, iterate through the list backward using a standard indexed for loop and use 'list.remove(index)'.
What is an infinite loop, and what are common causes of accidentally creating one in Java?
An infinite loop is a loop whose termination condition never becomes false, causing it to run indefinitely (until manually stopped or the program crashes from resource exhaustion). Common causes include: forgetting to update the loop control variable inside a while loop (e.g., forgetting 'i++'), writing a for loop's update statement incorrectly so it never actually changes the condition's outcome (like accidentally decrementing when the condition checks for an increasing value), or relying on a boolean flag variable that is never actually set to false anywhere within the loop's reachable code paths.
Write a Java program using a for loop that calculates and prints the sum of all even numbers from 1 to 20.
public class SumOfEvens { public static void main(String[] args) { int sum = 0; for (int i = 1; i <= 20; i++) { if (i % 2 == 0) { sum += i; } } System.out.println("Sum of even numbers: " + sum); } } // Output: // Sum of even numbers: 110
What will be the output of the following code, and identify if it has any issue? int i = 1; while (i < 5) { System.out.println("Value: " + i); }
This code creates an infinite loop, continuously printing 'Value: 1' forever, and will never terminate on its own. The issue is that 'i' is never updated (incremented) anywhere inside the loop body, so the condition 'i < 5' remains true indefinitely since 'i' always stays equal to 1. To fix it, an increment statement like 'i++;' must be added inside the loop body, e.g., after the println statement.
Write a Java program using an enhanced for-each loop that calculates the total sum of all elements in an integer array {10, 20, 30, 40, 50}.
public class ArraySum { public static void main(String[] args) { int[] numbers = {10, 20, 30, 40, 50}; int total = 0; for (int num : numbers) { total += num; } System.out.println("Total Sum: " + total); } } // Output: // Total Sum: 150

Loops — for, while, do-while, and the enhanced for-each — are essential control structures that allow Java programs to repeat actions efficiently without duplicating code. Choosing the right loop type depends on whether the iteration count is known in advance (for), depends on a dynamic condition checked before execution (while), requires guaranteed at-least-once execution (do-while), or simply needs to process every element of a collection (for-each). Avoiding common pitfalls like infinite loops and off-by-one errors is critical for writing reliable, bug-free repetitive logic.

© 2026 CompileX. Maintained by Aditya Kumar Sharma.