Unit 05 · lesson
Choose for, while, or Enhanced for by the Job
Java gives you more than one looping structure because iteration problems have different shapes.
The best structure is the one that exposes the control model clearly.
Counted iteration
When initialization, continuation, and update form one obvious counter, a for loop keeps them together:
for (int i = 0; i < 5; i++) {
IO.println(i);
}
Read the header as:
start: int i = 0
continue: i < 5
update after each pass: i++
Condition-controlled iteration
Use while when continuation depends on state that is not naturally a simple counter:
int battery = 3;
while (battery > 0) {
IO.println("run");
battery--;
}
The important state is battery level, not "iteration number."
Iterate through values directly
When you want every value in a collection and do not need its index, enhanced for can express that directly:
var names = List.of("Maya", "Lee", "Noor");
for (String name : names) {
IO.println(name);
}
Read it as:
for each
String nameinnames
The loop says less about storage positions and more about the task.
Do not choose by habit
Suppose you need to print every student name. An index loop works:
for (int i = 0; i < names.size(); i++) {
IO.println(names.get(i));
}
But if i is never used for anything except get(i), enhanced for exposes the intent more clearly.
Now suppose you need both position and value:
for (int i = 0; i < names.size(); i++) {
IO.println((i + 1) + ": " + names.get(i));
}
The index has a job, so the indexed loop is justified.
Same output, different design signal
Create three implementations that print 1 through 5:
- a
forloop; - a
whileloop; - enhanced
foroverList.of(1, 2, 3, 4, 5).
All can produce the same output. Compare them by:
- how obvious the stop condition is;
- how much mutable state is visible;
- whether the data already exists as a collection;
- whether an index matters.
AP.3 tradeoff evidence
Choose one of these tasks:
- examine every error code in a list;
- retry an operation until success or a maximum attempt count;
- create numbered report lines from a list;
- print exactly 20 simulation steps.
Implement it with the structure you believe fits best. Then name an alternative that would also work and explain why your choice is more readable or less error-prone for this requirement.
You are not proving that one Java keyword is universally better. You are proving that control structure follows the problem.