CHAPTER 08
Beginner
Loops in Java
Updated: May 17, 2026
5 min read
# CHAPTER 8
Loops in Java
1. Introduction
Loops let you execute a block of code repeatedly. Instead of writingSystem.out.println() 100 times, you write one loop. Loops are the workhorse of programming — processing lists, iterating through databases, and running game engines.
2. Learning Objectives
-
Use
for,while, anddo-whileloops.
-
Control flow with
breakandcontinue.
- Write nested loops.
- Build a multiplication table generator.
3. The for Loop
Best when you know exactly how many times to iterate.
java
Structure: for (initialization; condition; update) { body }
4. The while Loop
Best when you don't know how many iterations in advance.
java
5. The do-while Loop
Guarantees the body executes at least once.
java
6. Enhanced for-each Loop
Simplified syntax for iterating over arrays and collections.
java
7. break and continue
-
break: Immediately exits the entire loop.
-
continue: Skips the current iteration and jumps to the next one.
java
8. Nested Loops
java
9. Mini Project: Multiplication Table Generator
java
10. Infinite Loop
java
11. Common Mistakes
-
Off-by-one errors: Using
<vs<=incorrectly.
-
Infinite loops: Forgetting to update the loop variable in a
whileloop.
- Modifying the loop variable inside the body: Can cause unexpected behavior.
12. MCQ Quiz with Answers
Question 1
Which loop always executes at least once?
Question 2
What does break do?
Question 3
What does continue do?
Question 4
How many times does for(int i=0; i<5; i++) iterate?
Question 5
What is the for-each loop used for?
Question 6
What causes an infinite loop?
Question 7
Nested loops are:
Question 8
for(;;) creates:
Question 9
What is the output of for(int i=0; i<3; i++) { System.out.print(i); }?
Question 10
Which loop checks condition AFTER execution?
13. Interview Questions
-
Q: What is the difference between
whileanddo-while?
- Q: How do you avoid infinite loops?
-
Q: When should you use
forvswhile?
-
Q: Can
breakexit nested loops? (Answer: only the innermost one, use labeled break for outer)
14. Summary
Java providesfor, while, do-while, and enhanced for-each loops. break exits loops, continue skips iterations. Nested loops create multi-dimensional patterns. Always ensure loop termination conditions to avoid infinite loops.