Control Flow
Loops
Complete lesson for Loops using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.
Basics — Loops
Section: Control Flow. for, while, do-while, enhanced for, break, continue, and labeled loops.
The three classic loops
for— known count or index.while— test first.do-while— body runs at least once, then tests.- The condition must be
boolean. An infinite loop isfor (;;)orwhile (true).
| Loop | Test when | Body guaranteed? |
|---|---|---|
for (init; cond; step) | Before each iteration | No (if cond is first false) |
while (cond) | Before each iteration | No |
do { } while (cond); | After each iteration | Yes, once |
Enhanced for (for-each)
for (Type item : arrayOrIterable)visits each element. You get no index and must not structurally modify the collection (except through an Iterator).- Works on arrays and anything implementing
Iterable(ArrayList,HashSet, …).
public class LoopBasics {
public static void main(String[] args) {
int[] nums = {2, 4, 6};
for (int i = 0; i < nums.length; i++) {
System.out.print(nums[i] + " ");
}
System.out.println();
for (int n : nums) {
System.out.print(n + " ");
}
}
} break, continue, labels
breakleaves the innermost loop or switch.continueskips to the next iteration.- A label (
outer:) letsbreak outer;leave a nested loop — useful, but keep it rare and obvious.
Advanced — Loops
Off-by-one, mutation, and complexity
- The usual for-array pattern is
i = 0; i < a.length; i++. Using<=is the classic off-by-one /ArrayIndexOutOfBoundsException. - Do not remove from an
ArrayListwhile using for-each — you getConcurrentModificationException. Use anIteratoror iterate indexes backward. - Nested loops over n×n are O(n²). Say this out loud in interviews when you write them.
Tricky Interview Points
Q1) Difference between while and do-while?
Answer while tests first and may run zero times. do-while runs the body once, then tests.
Q2) What does the enhanced for loop require?
Answer An array or an Iterable. It hides the index and the Iterator.
Q3) How do you break out of two nested loops?
Answer Use a labeled break, or extract the loops to a method and return, or set a flag.
Q4) Is for(;;) legal?
Answer Yes. All three for-clauses are optional. for(;;) is an infinite loop.
Q5) Why is modifying a collection in for-each unsafe?
Answer The enhanced for uses an Iterator. Structural changes confuse fail-fast iterators and throw ConcurrentModificationException.
Q6) Can a for-each loop run backward?
Answer Not directly. Use a classic index loop from length-1 down to 0, or a ListIterator.
Simple Programs
Nested loop and labeled break
public class LabeledBreak {
public static void main(String[] args) {
outer:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i * j == 4) {
System.out.println("stop at " + i + "," + j);
break outer;
}
System.out.println(i + " x " + j);
}
}
}
} do-while input-style loop
public class DoWhileDemo {
public static void main(String[] args) {
int n = 3;
do {
System.out.println("tick " + n);
n--;
} while (n > 0);
}
} Problem Solving Tricks
- Prefer for-each when you do not need the index.
- Cache
list.size()only if you are sure the list does not change; forArrayListsize()is O(1) anyway. - Infinite loops need a clear
breakor they belong in servers (while (running)). - Use
IntStream.rangeonly when streams make the code clearer — classic for is fine.
Practice Programs List
- Print a multiplication table 1–10 with nested for.
- Sum an array with both classic for and for-each; confirm the same result.
- Write a do-while that prints 1..5.
- Find the first pair (i, j) with i + j == 10 using a labeled break.
- Count vowels in a
char[]with a loop andcontinueon consonants.