Ch 7 · Loops & Iterations · Java
Topic 7 of 13 in Java — Complete Tutorial (Beginner) — 3 lessons.
The for Loop
Computers are brilliant at repetition, and a loop runs a block of code many times automatically. The for loop is ideal when you know how many times to repeat. It packs three parts into one line: where to start, the condition to keep going, and how to change the counter each time. Java checks the condition before each repetition; the moment it is false, the loop ends.
while and do-while
The while loop repeats as long as a condition stays true, and you manage the change yourself inside the loop. It is best when you do not know in advance how many repetitions you need. The do-while loop is similar but checks the condition *after* running the body, so the body always runs at least once. The golden rule: make sure the condition will eventually become false, or you create an infinite loop.
Enhanced for, break & continue
When you want to walk through every item in an array or list, the enhanced for loop (the "for-each") is the cleanest choice: for (int n : numbers) gives you each element in turn with no index to manage. Inside any loop, break exits early (handy once you have found what you searched for) and continue skips the rest of the current repetition and moves to the next.