Lesson 57 min read

Loops

Do it again (and again and again)

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 — like while, but guarantees at least one run.

The Classic for Loop

public class Main {
public static void main(String[] args) {
// Count from 1 to 5
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
System.out.println("---");
// Countdown!
for (int i = 3; i >= 1; i--) {
System.out.println(i + "...");
}
System.out.println("Go!");
System.out.println("---");
// Skip by 2s (even numbers)
for (int i = 2; i <= 10; i += 2) {
System.out.print(i + " ");
}
System.out.println();
}
}
Output
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
---
3...
2...
1...
Go!
---
2 4 6 8 10

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

public class Main {
public static void main(String[] args) {
// While loop — keep halving until we're under 1
double value = 100.0;
int steps = 0;
while (value >= 1) {
value /= 2;
steps++;
}
System.out.println("Took " + steps + " halvings to get below 1");
System.out.println("Final value: " + value);
System.out.println("---");
// Do-while — always runs at least once
int number = 0;
do {
System.out.println("This runs even though number is " + number);
number++;
} while (number < 0); // condition is false, but body ran once!
System.out.println("---");
// Enhanced for-each — the cleanest loop
String[] pets = {"Dog", "Cat", "Fish", "Hamster"};
for (String pet : pets) {
System.out.println("I have a " + pet);
}
}
}
Output
Took 7 halvings to get below 1
Final value: 0.78125
---
This runs even though number is 0
---
I have a Dog
I have a Cat
I have a Fish
I have a Hamster

Break, Continue & Labeled Break

public class Main {
public static void main(String[] args) {
// break — emergency exit from the loop
System.out.print("Searching: ");
int[] numbers = {3, 7, 2, 9, 4, 1};
for (int n : numbers) {
System.out.print(n + " ");
if (n == 9) {
System.out.println("\nFound 9! Stopping.");
break;
}
}
// continue — skip this round, go to the next one
System.out.print("Odd numbers: ");
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // skip even numbers
}
System.out.print(i + " ");
}
System.out.println();
// Labeled break — escape from nested loops
System.out.println("Finding pair that sums to 7:");
outer:
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
if (i + j == 7) {
System.out.println(i + " + " + j + " = 7");
break outer; // breaks BOTH loops
}
}
}
}
}
Output
Searching: 3 7 2 9 
Found 9! Stopping.
Odd numbers: 1 3 5 7 9 
Finding pair that sums to 7:
2 + 5 = 7
Note: The number one loop mistake? Infinite loops. If your condition never becomes false, your program runs forever (or until your computer gives up). Always make sure something inside the loop is moving you toward the exit condition. A while(true) loop is only safe if you have a break inside.

Quick check

How many times does a do-while loop run if the condition is false from the start?
ConditionalsArrays