Navigation
Java Full Course: Mastering the Language Loops in Java
Loops in Java
(Complete Notes | Beginner to Advanced | Professional & Exam-Oriented | Masterclass)
1. Introduction to Looping
In programming, we often need to execute a block of code multiple times—whether it's processing items in an array, reading input until a condition is met, or repeatedly performing a calculation. This repeated execution is called looping (or iteration). Java provides several loop constructs that allow you to control how many times a block of code runs:
- while loop – repeats a block as long as a condition remains true; the condition is checked before each iteration.
- do-while loop – similar to while, but guarantees at least one execution because the condition is checked after the loop body.
- for loop – ideal when the number of iterations is known in advance; combines initialization, condition, and update in a single line.
- Enhanced for loop (for-each) – simplifies iteration over arrays and collections, focusing on the elements rather than the index.
Looping constructs are fundamental to writing efficient, concise, and maintainable code. They allow you to avoid repetitive code and handle dynamic data sets gracefully.
In the following sections, we will explore each loop type in detail, covering syntax, flow, common use cases, and best practices.
2. The while Loop
The while loop is a fundamental iterative construct that repeatedly executes a block of code as long as a specified condition remains true. It is an entry controlled loop, meaning the condition is evaluated before each iteration. If the condition is false initially, the loop body is never executed.
2.1 Syntax
- condition – a boolean expression. The loop continues as long as this evaluates to
true. - The loop body can be a single statement or a block enclosed in curly braces
{}. Using braces is recommended even for a single statement. - The loop will terminate when the condition becomes
false.
2.2 Flow of Control
Key points:
- Condition checked first.
- If true, loop body executes, then condition checked again.
- If false, loop ends and control passes to the next statement after the loop.
2.3 Basic Example
Output:
2.4 Infinite Loop
If the condition never becomes false, the loop runs forever (or until the program is terminated). This is often a programming error, but sometimes intentional (e.g., server loops).
To exit an infinite loop, use a break statement or a return.
2.5 Common Use Cases
a) Iterating with a Counter
b) Reading Input Until Sentinel
c) Validating User Input
d) Processing Elements of a Collection (When Index Not Needed)
2.6 Common Pitfalls
a) Forgetting to Update the Condition Variable
b) Off by One Errors
Always verify the loop's initial value and condition to ensure the correct number of iterations.
c) Using = Instead of == in Condition
Use == for comparison, or simply while (flag).
d) Semicolon After Condition
The semicolon creates an empty body; the loop spins forever (or until condition false) doing nothing. The following block executes only once after the loop.
2.7 Nested while Loops
A while loop can contain another loop inside its body.
Output:
2.8 break and continue in while
- break – exits the loop immediately.
- continue – skips the rest of the current iteration and jumps to the condition check.
2.9 Performance Considerations
- The
whileloop is as efficient as other loops; the main overhead is the condition evaluation. - Avoid placing expensive operations inside the condition unless necessary.
- For large loops, keep the loop body concise and avoid unnecessary method calls.
2.10 Best Practices
- Always use braces
{}even for single statements to prevent errors when adding more code. - Ensure loop termination – the loop should eventually make the condition false. Use a counter or a flag that changes inside the loop.
- Avoid complex conditions – store complex boolean logic in a variable for readability.
- Use
whilewhen the number of iterations is not known beforehand and depends on dynamic conditions. - Prefer
forloop when iterating a fixed number of times (e.g., arrays with indices) for clarity. - Minimize the scope of variables used only in the loop; declare them just before the loop or inside the loop body as needed.
2.11 Examples
Example 1: Sum of digits
Example 2: Reversing a number
Example 3: Simple menu system
2.12 Key Points to Remember
whileis an entry controlled loop; condition is evaluated before each iteration.- The loop may never execute if the condition starts as false.
- Ensure the loop condition eventually becomes false to avoid infinite loops.
- Use
breakto exit early,continueto skip the remainder of an iteration. - For counters or index based iteration, a
forloop is often more concise. - Always use braces
{}to define the loop body clearly.
3. The do-while Loop
The do-while loop is a post test (exit controlled) loop: it executes the loop body at least once, then checks the condition. If the condition remains true, the loop repeats; otherwise, it terminates. This makes it ideal for scenarios where you need to ensure the loop body runs before evaluating a termination condition.
3.1 Syntax
- The loop body is executed first.
- After the body, the
condition(a boolean expression) is evaluated. - If
conditionistrue, the loop repeats; iffalse, control exits the loop. - A semicolon
;is required after thewhile (condition).
3.2 Flow of Control
Key difference from while: the condition is evaluated after the loop body, guaranteeing at least one execution.
3.3 Basic Example
Output:
Even if count started at 6, the loop would still execute once.
3.4 When to Use do-while
Use do-while when you need the loop body to execute at least once regardless of the condition. Common scenarios:
- Menu driven programs – show the menu first, then get user choice.
- Input validation – prompt for input, then validate; repeat if invalid.
- Games – run the game logic at least once, then check if the player wants to continue.
3.5 Examples
a) Simple Menu System
b) Input Validation (Repeat Until Valid)
c) Guessing Game
3.6 Infinite Loop with do-while
To exit, use break or return inside the loop.
3.7 Difference Between while and do-while
| Feature | while | do-while |
|---|---|---|
| Condition check | At the beginning (entry controlled) | At the end (exit controlled) |
| Minimum executions | 0 (if condition initially false) | 1 (always executes at least once) |
| Semicolon after | No | Yes, after while (condition); |
| Typical use | When number of iterations unknown, may be zero | When at least one iteration is required |
3.8 Common Pitfalls
a) Missing Semicolon
b) Infinite Loop Due to Condition Not Updated
c) Confusing with while Leading to Off by One
If you need zero or more iterations, use while. Using do-while when the loop should possibly run zero times will cause an extra execution.
d) Variable Scope
Variables declared inside the do block are not accessible in the while condition. Declare them before the loop if needed in the condition.
3.9 break and continue in do-while
- break – exits the loop immediately.
- continue – skips the rest of the current iteration and jumps to the condition evaluation (since it's a post test loop, it will check the condition next).
3.10 Nested do-while Loops
do-while loops can be nested inside each other or inside other loops.
Output:
3.11 Best Practices
- Use
do-whilewhen the loop must execute at least once – for menus, input prompts, and validation. - Always use braces
{}for the loop body, even for a single statement. - Declare loop control variables outside the loop if they are needed in the condition.
- Keep the loop body concise; extract complex logic into methods.
- Avoid infinite loops – ensure the condition eventually becomes false or provide an exit via
break. - Prefer
whilefor zero or more iterations; usedo-whileonly when a first execution is mandatory.
3.12 Performance Considerations
do-whilehas the same performance characteristics aswhile.- For large loops, avoid expensive operations inside the condition or the loop body.
3.13 Key Points to Remember
do-whileguarantees at least one execution of the loop body.- Condition is checked after the body; a semicolon follows the
while(condition);. - Use it for scenarios like menus, input validation, or any process that must run once before checking termination.
- Variables declared inside the
doblock are not visible in the condition. - Be mindful of infinite loops; update the condition variable inside the body.
breakexits the loop;continueskips to the condition check.
4. The for Loop
The for loop is a powerful iteration construct that combines initialization, condition checking, and update in a single line. It is typically used when the number of iterations is known in advance (counter controlled loops). Java provides two flavors: the traditional for loop and the enhanced for loop (for each), introduced in Java 5.
4.1 Traditional for Loop Syntax
- initialization – executed once at the beginning. Usually declares and initializes a loop control variable.
- condition – a boolean expression evaluated before each iteration. If true, the loop body executes; if false, the loop terminates.
- update – executed after each iteration (before the next condition check). Typically increments or decrements the loop control variable.
All three parts are optional, but the semicolons are required.
Flow of Control
4.2 Basic Examples
Example 1: Print numbers 1 to 5
Example 2: Sum of first 10 natural numbers
Example 3: Iterating backwards
4.3 Variations of the for Loop
a) Multiple Initialization and Update Expressions
You can initialize or update multiple variables using commas.
b) Omitting Parts
Any part can be omitted, but the semicolons remain.
- Omitting initialization (variable declared before loop):
- Omitting condition (creates infinite loop; use break to exit):
- Omitting update (update inside body):
- Omitting all three (infinite loop):
c) Using the Comma Operator
The comma is used to separate multiple expressions in the initialization and update sections. It is not an operator in the condition section.
4.4 Scope of Loop Variable
A variable declared inside the for loop's initialization is local to the loop and cannot be accessed outside.
If you need the variable after the loop, declare it before the loop:
4.5 Common Pitfalls
a) Off by One Errors
Be careful with the condition and initial value.
b) Using = Instead of == in Condition
c) Modifying the Loop Variable Inside the Body
Changing the loop variable inside the body can lead to unexpected behavior.
d) Semicolon After the Parentheses
e) Floating Point Loop Control
Using floating point variables as loop counters can cause precision issues.
Prefer integer counters.
4.6 Nested for Loops
A for loop can contain another loop inside its body. Nested loops are common for processing multi dimensional data.
Example: Multiplication table
Output:
Example: Pattern printing
4.7 break and continue in for Loops
- break – terminates the loop immediately.
- continue – skips the rest of the current iteration and jumps to the update, then condition.
In nested loops, break and continue apply only to the innermost loop unless used with labels.
4.8 Enhanced for Loop (for-each)
Introduced in Java 5, the enhanced for loop simplifies iterating over arrays and collections when you only need the elements, not the index.
Syntax
- Type – the element type of the array or collection.
- variable – takes each element value in sequence.
- iterable – an array or an object implementing
Iterable(e.g.,Collection).
Examples
Array:
Collection (List):
[!IMPORTANT] The loop variable is a copy of the element. Modifying it does not change the original array/collection.
To modify elements, use the traditional for loop with an index.
When to Use Enhanced for
- When you need to iterate through all elements.
- When you do not need the index or modify the collection structure.
When to Use Traditional for
- When you need the index.
- When you need to modify elements (for arrays).
- When you need to iterate over a range or with a custom step.
4.9 Performance Considerations
- The traditional
forloop and enhancedforloop have similar performance for arrays andArrayList. - For linked structures (e.g.,
LinkedList), the enhanced for is efficient because it uses the iterator. - Avoid placing expensive method calls in the condition or update parts; compute once and store if possible.
4.10 Best Practices
- Keep the loop simple – the initialization, condition, and update should be clear.
- Use the enhanced for loop when you only need to read elements.
- Declare loop variables inside the
forto limit their scope. - Avoid modifying the loop variable inside the body unless absolutely necessary.
- Use integer counters for loops to avoid floating point precision issues.
- Use meaningful variable names –
i,j,kfor simple loops, but descriptive names for complex ones. - Prefer
foroverwhilewhen the number of iterations is known – it keeps all loop control logic together.
4.11 Summary Table: for Loop Features
| Feature | Traditional for | Enhanced for (for-each) |
|---|---|---|
| Syntax | for(init; cond; update) { } | for(Type var : iterable) { } |
| Access to index | Yes (via loop variable) | No |
| Modify elements | Yes (through index) | No (copy) |
| Use case | Counter controlled loops, range iteration | Iterating over all elements of array/collection |
| Scope of loop variable | In initialization (if declared there) | Inside loop only (variable is local) |
| Complexity | More flexible (multiple expressions, skip parts) | Simpler, less error prone |
4.12 Key Points to Remember
- The traditional
forloop combines initialization, condition, and update in one line, making it ideal for counter based iteration. - All three parts are optional; an empty
for(;;)creates an infinite loop. - Variables declared in the initialization are local to the loop.
- Use the enhanced
forloop for simple read only iteration over arrays and collections. - Be mindful of off by one errors, modifying the loop variable, and using floating point counters.
breakandcontinuework inforloops as in other loops.- Nested
forloops are common for working with multi dimensional data.
5. Nested Loops
A nested loop is a loop inside the body of another loop. The outer loop controls how many times the inner loop executes. Nested loops are essential for processing multi dimensional data (like matrices), generating patterns, and performing complex iterative tasks.
5.1 Basic Concept
When a loop contains another loop, the inner loop completes all its iterations for each iteration of the outer loop.
Output:
- Outer loop runs 3 times.
- For each outer iteration, the inner loop runs 2 times.
- Total iterations: 3 × 2 = 6.
5.2 Types of Nested Loops
You can nest any combination of loop types: for, while, do-while.
a) for inside for (most common)
b) while inside for
c) do-while inside for
d) Any combination (e.g., while inside while)
5.3 Common Use Cases
a) Multiplication Table
b) Pattern Printing (Triangle)
c) Inverted Triangle
d) Matrix Operations (Sum, Transpose, Multiplication)
e) Finding Prime Numbers (Sieve of Eratosthenes style)
5.4 Controlling Nested Loops: break and continue
By default, break and continue affect only the innermost loop.
To break out of an outer loop, use labeled breaks or a flag.
a) Labeled break
b) Labeled continue
5.5 Performance Considerations
- Nested loops multiply complexity: if outer loop runs
ntimes and inner runsmtimes, total operations =n × m. - Avoid deep nesting (more than 2 or 3 levels) for readability and performance.
- Move invariant computations out of the inner loop (e.g., compute a constant value before the inner loop).
- For large data, consider alternative algorithms (e.g., using
Streamor specialised data structures).
Example of optimizing invariant:
5.6 Common Pitfalls
a) Variable Scope
Variables declared inside the inner loop are local and cannot be used outside.
b) Confusing Loop Counts
Be mindful of the total number of iterations; an inner loop that runs many times can cause performance issues.
c) Using the Same Variable Name in Nested Loops
While allowed, it can be confusing. Use distinct names (i, j, k) or meaningful names (row, col).
d) Off by One in Boundaries
Especially when processing arrays, ensure indices stay within bounds.
e) Unintended Infinite Loops
If the inner loop modifies the outer loop's control variable, you may get unexpected infinite loops.
5.7 Best Practices
- Use meaningful variable names for nested loops, especially when more than two levels. For simple counters,
i,j,kare acceptable. - Limit nesting depth – refactor deeply nested loops into separate methods when possible.
- Use labels sparingly; they can make code harder to follow. Often a flag or a method return is clearer.
- Keep the inner loop body concise – if it becomes long, extract it into a method.
- Consider enhanced for for iterating over collections and arrays without indices when you don't need the index.
5.8 Advanced: Nested Loops with Different Iteration Patterns
You can have loops with different step sizes, or where the inner loop's range depends on the outer loop's index.
5.9 Examples in Real Applications
- Image processing: iterating over pixels in a 2D image (rows and columns).
- Game development: checking collisions between objects in a grid.
- Database operations: processing result sets and related sub records.
- Sorting algorithms: nested loops in bubble sort, insertion sort, etc.
5.10 Summary
- A nested loop is a loop inside another loop.
- The inner loop completes all its iterations for each iteration of the outer loop.
- Any combination of loop types (
for,while,do-while) can be nested. - Nested loops are used for multi dimensional data, pattern generation, and complex iterations.
- Use labels only when necessary to break/continue outer loops.
- Keep nesting depth manageable for readability and performance.
- Be cautious about total iteration count and off by one errors.
