Repetition Without Boredom – Mastering Loops in Java

Your code can now make decisions. Awesome! But what if you want your program to do something more than once? Maybe a lot more than once? You could just copy and paste the code a few times. Or… you could use loops.

What You’ll Learn

Why Loops?

Imagine trying to print numbers from 1 to 100 with just System.out.println() — your fingers would fall off. Loops let you:

What Is a Loop?

A loop is a control structure that repeats a block of code as long as a condition is true. All loops share three essential components:

These parts help the loop start, keep going, and stop when it should.

The while Loop

Use a while loop when you don’t know how many times the code should repeat.

while loop structure

The for Loop

Use a for loop when you know how many times to repeat

for loop structure

This is functionally the same as a while loop but more compact and easier to manage when counting.

The do-while Loop

Use a do-while loop when the code should run at least once no matter what.

do-while loop structure

Which Loop Should I Use?

Use a for loop

Use a while loop

Use a do-while loop

Each loop has a personality. Pick the one that fits your vibe for the task.

break and continue

Use these to control the flow of loops:

break and continue example

Output:

break and continue output

Common Mistakes

Practice Time!

Try writing code that:

Counts from 10 to 1
Repeats until the user types “exit”
Sums numbers from 1 to 100
Creates a simple multiplication table

What’s Next

Now that you can repeat code, it's time to organize and reuse it better. In the next chapter, you'll learn about methods — reusable blocks of code that make your programs cleaner, smarter, and easier to maintain.