Loops
java loops for while do-while for-each enhanced break continue nested infinite loop iteration array collection
Introduction
In the previous lesson, you learned how Java makes decisions using if-else and switch statements.
However, many real-world applications require executing the same block of code repeatedly.
Imagine:
- Printing invoices for 100 customers
- Reading thousands of records from a database
- Processing files line by line
- Validating multiple user inputs
- Iterating through collections
Writing the same code repeatedly is inefficient and difficult to maintain.
Java provides loops to automate repetitive tasks.
A loop executes a block of code multiple times until a specified condition becomes false.
In this lesson, you'll learn:
- Why loops are needed
- Types of loops
forloopwhileloopdo-whileloop- Enhanced
forloop (For-Each) - Nested loops
- Infinite loops
- Loop control statements (
break&continue) - Real-world examples
- Best practices
- Common mistakes
- Hands-on exercises
- Professional interview questions
What is a Loop?
A loop repeatedly executes a block of code while a condition remains true.
Instead of writing:
System.out.println("Welcome");System.out.println("Welcome");System.out.println("Welcome");System.out.println("Welcome");System.out.println("Welcome");
Use a loop:
for (int i = 1; i <= 5; i++) {System.out.println("Welcome");}
Output:
WelcomeWelcomeWelcomeWelcomeWelcome
Types of Loops in Java
Java provides four looping mechanisms:
forLoopwhileLoopdo-whileLoop- Enhanced
forLoop (For-Each)
Each serves different use cases.
The for Loop
The for loop is ideal when the number of iterations is known.
Syntax:
for(initialization; condition; update) {// Code}
Example:
for (int i = 1; i <= 5; i++) {System.out.println(i);}
Output:
12345
How a for Loop Works
Execution order:
- Initialization executes once.
- Condition is checked.
- Loop body executes.
- Update expression executes.
- Repeat until the condition becomes false.
Flow:
Initialization↓Condition↓True↓Execute Body↓Update↓Condition Again
The while Loop
Use a while loop when the number of iterations is unknown.
Syntax:
while(condition) {// Code}
Example:
int count = 1;while (count <= 5) {System.out.println(count);count++;}
Output:
12345
The do-while Loop
A do-while loop executes the code at least once, even if the condition is false.
Syntax:
do {// Code} while(condition);
Example:
int number = 1;do {System.out.println(number);number++;} while (number <= 5);
Output:
12345
Difference Between while and do-while
| while | do-while |
|---|---|
| Checks condition first | Executes first, checks later |
| May execute zero times | Executes at least once |
Enhanced for Loop (For-Each)
The enhanced for loop is used to iterate through arrays and collections.
Example:
String[] fruits = {"Apple", "Banana", "Orange"};for (String fruit : fruits) {System.out.println(fruit);}
Output:
AppleBananaOrange
Advantages:
- Cleaner syntax
- No index management
- Less error-prone
Nested Loops
A loop inside another loop is called a nested loop.
Example:
for (int i = 1; i <= 3; i++) {for (int j = 1; j <= 3; j++) {System.out.print("* ");}System.out.println();}
Output:
* * ** * ** * *
Nested loops are commonly used for matrices, tables, and patterns.
Infinite Loops
A loop that never terminates is called an infinite loop.
Example:
while (true) {System.out.println("Running...");}
Use infinite loops carefully in servers, event listeners, or applications waiting for events.
Using break
The break statement immediately exits the loop.
Example:
for (int i = 1; i <= 10; i++) {if (i == 6) {break;}System.out.println(i);}
Output:
12345
Using continue
The continue statement skips the current iteration and proceeds to the next one.
Example:
for (int i = 1; i <= 5; i++) {if (i == 3) {continue;}System.out.println(i);}
Output:
1245
Real-World Example: ATM PIN Validation
int attempts = 0;while (attempts < 3) {System.out.println("Enter PIN");attempts++;}
Real-World Example: Processing Orders
String[] orders = {"Laptop", "Mobile", "Keyboard"};for (String order : orders) {System.out.println("Processing: " + order);}
Best Practices
- Use
forwhen the iteration count is known. - Use
whilewhen the iteration count depends on a condition. - Use
do-whilewhen the loop must execute at least once. - Prefer the enhanced
forloop for arrays and collections when you don't need the index. - Keep loop bodies small and readable.
- Avoid unnecessary nested loops for better performance.
Common Mistakes
Forgetting to Update the Loop Variable
while (i < 5) {System.out.println(i);}
This creates an infinite loop.
Wrong Loop Condition
Using < instead of <= (or vice versa) may result in missing or extra iterations.
Modifying Collections Incorrectly
Changing a collection while using an enhanced for loop may throw a ConcurrentModificationException.
Deeply Nested Loops
Excessive nesting reduces readability and may affect performance.
Hands-on Exercise
Create a Java program that:
- Prints numbers from 1 to 100 using a
forloop. - Prints even numbers using a
whileloop. - Demonstrates a
do-whileloop with user input. - Uses an enhanced
forloop to print an array of employee names. - Uses nested loops to print a multiplication table.
- Demonstrates the use of
breakandcontinue. - Creates a simple menu that repeats until the user selects "Exit".
Summary
Loops are one of the most fundamental programming constructs in Java. They eliminate repetitive code, improve readability, and make programs scalable. Choosing the right type of loop depends on whether the number of iterations is known, unknown, or guaranteed to execute at least once.
Key Takeaways
- Loops automate repetitive tasks.
forloops are best for fixed iterations.whileloops are ideal for condition-based repetition.do-whileloops execute at least once.- Enhanced for loops simplify array and collection traversal.
breakexits a loop immediately.continueskips the current iteration.- Nested loops are useful for matrices and pattern generation.
Professional Interview Questions
1What is the difference between for, while, and do-while loops?
Professional Answer
A for loop is preferred when the number of iterations is known in advance. A while loop is used when the loop depends on a condition that may change dynamically. A do-while loop guarantees at least one execution because the condition is evaluated after the loop body.
Follow-up Questions
- When would you use a do-while loop?
- Can a while loop execute zero times?
Interview Tip: Explain that selecting the appropriate loop improves readability and clearly expresses the program's intent.
2What is the difference between break and continue?
Professional Answer
The break statement immediately terminates the loop, while the continue statement skips the current iteration and proceeds with the next iteration.
Follow-up Questions
- Can break be used in a switch statement?
- Can continue be used outside loops?
Interview Tip: Mention that excessive use of break and continue may reduce code readability.
3What is the Enhanced for Loop?
Professional Answer
The enhanced for loop, also known as the for-each loop, simplifies iterating over arrays and collections. It removes the need for index management, resulting in cleaner and less error-prone code.
Follow-up Questions
- Can you modify the collection while using a for-each loop?
- When is a traditional for loop more suitable?
Interview Tip: State that the enhanced for loop is ideal for read-only traversal, while a traditional for loop is preferred when index access or element modification is required.