Loops
Why Loops?
Imagine you have to write "I will not throw paper airplanes" 100 times on the board. You could write 100 System.out.println() lines... or you could use a loop and write it once.
Loops let your code repeat a block of instructions. Java gives you three flavors:
for— best when you know how many times to repeat.while— best when you repeat until some condition changes.do-while— likewhile, but guarantees at least one run.
The Classic for Loop
While, Do-While & For-Each
A while loop is like a guard at a door who keeps checking: "Is the condition still true? OK, go again." It checks before each run, so if the condition is false from the start, the body never executes.
A do-while loop is the opposite — it runs the body first, then checks. Think of it like a restaurant that gives you one free sample before asking if you want more.
The enhanced for-each loop is the simplest way to go through every item in an array or collection. You don't need an index counter — Java hands you each item directly.
While, Do-While & For-Each
Break, Continue & Labeled Break
while(true) loop is only safe if you have a break inside.