Lesson content
Read, practise, then check your understanding
Use for for counting, while for condition-driven repetition, and do-while when the body must run once. Enhanced for traverses arrays and Iterable values without indexing.
Safe iteration
int[] values = {2, 4, 6};
int total = 0;
for (int value : values) {
total += value;
}
for (int i = 0; i < values.length; i++) {
if (values[i] == 0) continue;
if (values[i] < 0) break;
}
State the loop invariant, verify empty and boundary cases, and ensure each iteration progresses. break exits the nearest loop; continue advances it. Labels can target an outer loop but often signal logic that should be extracted. Do not structurally modify most collections inside enhanced for; use an iterator’s supported removal or a bulk operation. Nested full-size loops usually multiply complexity, so consider sets, maps, or stream operations when they express a more efficient algorithm.
Knowledge check
Answer every question correctly to complete this chapter.
0 of 10 checks passed
Your progress is saved on this device.