Loops in Java
Repeat logic using for, while, do-while, and enhanced for-each loops, with break, continue, and labelled loop control.
for Loop
The `for` loop is the most common loop in Java. It bundles the initializer, condition, and update into one line, making it ideal when the number of iterations is known in advance.
1. How a for Loop Works Internally
The three parts of a `for` header: initializer runs once, condition is checked before each iteration, update runs after each iteration.
2. Traversing an Array with for
Use the index to access each element of an array inside a `for` loop.
3. Nested for Loops
Place a `for` loop inside another to work with 2D structures or generate combinations.
while Loop
The `while` loop checks its condition before each iteration. Use it when the number of iterations is not known in advance — for example, reading input until the user types "quit", or processing data until a stream ends.
1. How a while Loop Works
The condition is checked first. If it is false from the start, the body never runs.
2. while with Unknown Iterations
The classic use case: keep looping until a condition is met.
do-while Loop
The `do-while` loop runs its body first and checks the condition after each iteration. This guarantees the body executes at least once — unlike `while`, which may never run if the condition is initially false.
1. do-while Execution
Body runs first, condition is checked at the bottom.
2. do-while vs while
Any do-while can be rewritten as a while loop with the body duplicated before the loop.
Enhanced for-each Loop
The enhanced `for` loop (also called for-each) was introduced in Java 5. It is the cleanest way to iterate over arrays and any `Iterable` (lists, sets, etc.) when you do not need the index.
1. for-each with Arrays
Iterate every element without touching an index variable.
2. for-each with Collections
for-each works on any `Iterable` — List, Set, Map entries, etc.
3. Iterating Characters of a String
Use `toCharArray()` to iterate each character with for-each.
break & continue
`break` immediately exits the innermost loop. `continue` skips the rest of the current iteration and moves to the next. Java also supports **labelled** `break` and `continue` to control outer loops from inside nested ones.
1. break
Exit the loop immediately when a condition is met.
2. continue
Skip the rest of the current iteration and jump straight to the next.
3. Labelled break & continue
Labels let you break or continue an outer loop from inside a nested one.
Reverse Loops
Sometimes you need to process elements from the end to the beginning — for example, printing a countdown, reversing output, or removing elements from a list while iterating.
1. Reverse for Loop on Numbers
Start the counter at the end and decrement each iteration.
forEach on Collections
`forEach()` is a method on `Iterable` and `Map` (Java 8+) that accepts a lambda. It is an alternative to the for-each loop when you want a more functional, pipeline-friendly style.
1. forEach on Lists & Arrays
Call `.forEach()` with a lambda instead of writing an explicit loop.
2. forEach on Maps
Iterate key-value pairs directly with a `BiConsumer` lambda.
Best Practices
Picking the right loop type and following a few simple rules keeps loop code readable, correct, and efficient.
1. Loop Selection Guidelines
A quick reference for choosing the right loop in each situation.