while, do-while, and for loops in Javabreak and continue to control loop flowfor loop (for-each) with arraysloop — a block of code that repeats | iteration — one pass through a loop body | pre-test loop — condition checked before the body runs | post-test loop — condition checked after the body runs | sentinel value — a special input that signals "stop looping" | infinite loop — a loop whose condition never becomes false | accumulator — a variable that collects a running total | nested loop — a loop inside another loop | break — exits a loop immediately | continue — skips the rest of the current iteration | off-by-one error — looping one too many or one too few times | enhanced for loop — a simplified loop that iterates over a collection
A loop repeats a block of code. Instead of writing the same lines over and over, you write them once and tell Java how many times — or under what conditions — to keep running them.
Here is the difference without and with a loop. Imagine printing "Hello!" five times:
// Without a loop — tedious, doesn't scale
System.out.println("Hello!");
System.out.println("Hello!");
System.out.println("Hello!");
System.out.println("Hello!");
System.out.println("Hello!");
// With a loop — one statement, any number of times
for (int i = 0; i < 5; i++) {
System.out.println("Hello!");
}
Want to print it a thousand times? Change one number. The code stays the same size.
| Loop | When Condition Is Checked | Best Used When… |
|---|---|---|
while | Before each iteration (pre-test) | You don't know in advance how many times to loop |
do-while | After each iteration (post-test) | The body must run at least once (e.g., input validation) |
for | Before each iteration (pre-test) | You know exactly how many iterations you need |
A loop is like hitting snooze on your alarm. The condition is "Am I actually awake yet?" If no, sleep nine more minutes and check again. You keep repeating that cycle until the condition is true — then you stop looping and get up. The alarm checks the condition before it lets you sleep (while), or it rings once and then decides whether to ring again (do-while).
while LoopThe while loop is the fundamental loop in Java. It checks a condition before each iteration. If the condition is true, the body runs. Then it checks again. This continues until the condition is false.
while (condition) {
// body — runs as long as condition is true
}
Because the condition is checked before the body runs, a while loop is called a pre-test loop. If the condition is false on the very first check, the body never executes at all.
When you use a counter variable to control a while loop, you need four things: initialize, check, do work, update.
int count = 1; // 1. Initialize before the loop
while (count <= 5) { // 2. Check the condition
System.out.println(count); // 3. Do the work
count++; // 4. Update — or you get an infinite loop!
}
Trace it mentally: count starts at 1, prints 1, becomes 2. Prints 2, becomes 3. … Prints 5, becomes 6. Condition 6 <= 5 is false — loop ends.
When you don't know in advance how many times to loop, use a sentinel value — a special input that signals "I'm done." The loop keeps running until it sees that value.
import java.util.Scanner;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number (-1 to quit): ");
int number = sc.nextInt();
while (number != -1) { // -1 is the sentinel
System.out.println("You entered: " + number);
System.out.print("Enter a number (-1 to quit): ");
number = sc.nextInt();
}
System.out.println("Goodbye!");
Notice that the prompt and read appear twice: once before the loop (to get the first value) and once at the end of the loop body (to get the next value). This is the standard pattern for sentinel loops.
If the loop condition never becomes false, the program runs forever. The most common cause is forgetting to update the variable the condition depends on:
int x = 1;
while (x < 10) {
System.out.println(x);
// BUG: x never changes, so x < 10 is always true — infinite loop!
}
In IntelliJ, click the red square in the Run window to stop the program. Then find your missing update statement.
Write a while loop that counts down from 10 to 1, printing each number on its own line. After the loop ends, print "Blastoff!"
do-while LoopThe do-while loop is almost identical to while, with one important difference: it runs the body first, then checks the condition. That makes it a post-test loop — the body always executes at least once.
do {
// body — runs at least once, guaranteed
} while (condition); // <-- note the semicolon here!
The semicolon after the closing parenthesis is required. Java will give you a compile error if you leave it out.
You need to show the user a prompt at least once before you can check what they typed. do-while handles this perfectly:
import java.util.Scanner;
Scanner sc = new Scanner(System.in);
int age;
do {
System.out.print("Enter your age (0-120): ");
age = sc.nextInt();
} while (age < 0 || age > 120); // keep asking if invalid
System.out.println("Age recorded: " + age);
With a regular while loop, you would have to read the first value before the loop and read again inside the loop — duplicating the prompt and read statements. do-while keeps it in one place.
| Feature | while |
do-while |
|---|---|---|
| Loop type | Pre-test | Post-test |
| Condition check | Before each iteration | After each iteration |
| Minimum iterations | 0 — may never run | 1 — always runs once |
| Semicolon after condition? | No | Yes, required |
| Best for | General looping | Input validation, menus |
Ask yourself: "Does the body have to run at least once before I can even check the condition?" If yes, do-while is your loop. Showing a menu is the textbook example — you must display the options before you can tell the user to pick one, and then validate their pick.
Write a do-while loop that displays three menu options (1, 2, 3) and keeps asking until the user enters a valid choice. Print a confirmation once a valid choice is made.
for LoopWhen you know exactly how many times to loop, the for loop is the cleanest choice. It bundles the initialization, condition check, and update all into one header line.
for (initialization; condition; update) {
// body
}
true.| Step | What Happens | Frequency |
|---|---|---|
| 1 | Initialization runs | Once, at the very start |
| 2 | Condition is evaluated | Before every iteration |
| 3 | Body executes | Each time condition is true |
| 4 | Update runs | After each body execution |
| 5 | Go back to step 2 | Until condition is false |
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
for (int i = 5; i >= 1; i--) {
System.out.println(i);
}
System.out.println("Done!");
for (int i = 0; i <= 10; i += 2) {
System.out.print(i + " ");
}
System.out.println();
Use for when the number of iterations is known before the loop starts. Use while when the loop should continue based on something you discover while running. In practice: counting, iterating over arrays → for; reading input until valid, processing until a sentinel → while.
The for header's update expression already handles the counter. Changing it inside the body too causes hard-to-find bugs:
// BAD — skips every other number
for (int i = 0; i < 10; i++) {
System.out.println(i);
i++; // oops — double increment, skips 1, 3, 5, 7, 9
}
Let the header manage the counter. Keep your logic in the body.
break and continueSometimes you need to exit a loop before the condition naturally becomes false, or skip the rest of one iteration and jump straight to the next. break and continue handle those cases.
When Java hits break, it exits the loop entirely. Execution jumps to the first statement after the closing brace.
for (int i = 1; i <= 10; i++) {
if (i == 7) {
System.out.println("Found 7! Stopping early.");
break;
}
System.out.println(i);
}
System.out.println("After the loop.");
A common use: searching an array for a value. Once you find it, break so you don't waste time checking the rest.
continue skips the remaining statements in the current iteration. In a for loop, it jumps to the update step. In a while loop, it jumps back to the condition check.
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // skip the rest of this iteration for even numbers
}
System.out.print(i + " ");
}
System.out.println();
break and continue are legitimate tools, but overusing them makes loops hard to read and reason about. If you're reaching for them frequently, your condition logic probably needs a rewrite instead.
| Keyword | Effect | When It Helps |
|---|---|---|
break | Exits the loop entirely | Early exit after finding a result; error condition |
continue | Skips rest of current iteration | Skip invalid or irrelevant values without nesting |
In nested loops, break exits the loop it is directly inside — not all loops at once. If you need to break out of two levels, you'll need a flag variable or labeled breaks (an advanced feature).
A nested loop is a loop inside another loop. The outer loop drives the rows; the inner loop drives the columns. Every time the outer loop runs once, the inner loop runs all the way through.
Outer runs 3 times × inner runs 4 times = 12 total executions of the inner body. This multiplying effect matters a lot when you're dealing with large data sets — but for classroom-sized examples it's perfectly fine.
for (int outer = 1; outer <= 3; outer++) {
for (int inner = 1; inner <= 4; inner++) {
System.out.println("outer=" + outer + ", inner=" + inner);
}
}
for (int row = 1; row <= 5; row++) {
for (int col = 1; col <= 5; col++) {
System.out.printf("%4d", row * col);
}
System.out.println(); // move to next row after each row is complete
}
The inner loop runs a different number of times on each row — exactly row times — because the inner loop's limit is the outer loop variable:
for (int row = 1; row <= 5; row++) {
for (int star = 1; star <= row; star++) {
System.out.print("*");
}
System.out.println();
}
Fix the outer variable at its first value. Walk through all inner values. Write down what prints. Then advance the outer variable and repeat. A small table with columns for each loop variable is the fastest way to do this on an exam.
Write nested loops to print a 4x4 grid where each cell shows the product of its row and column (both starting at 1). Row 2, col 3 should show 6.
These patterns appear constantly in real programs. Learn to recognize and write them without thinking.
Initialize a variable to zero before the loop. Add each new value to it inside the loop.
int sum = 0; // accumulator — starts at 0
for (int i = 1; i <= 10; i++) {
sum += i;
}
System.out.println("Sum 1 to 10: " + sum);
Same idea as an accumulator, but you only add 1 when a specific condition is met.
int evenCount = 0;
for (int i = 1; i <= 20; i++) {
if (i % 2 == 0) {
evenCount++;
}
}
System.out.println("Even numbers from 1-20: " + evenCount);
Initialize max to the first value (or the smallest possible integer). Update it whenever you find something bigger.
import java.util.Scanner;
Scanner sc = new Scanner(System.in);
System.out.print("How many numbers? ");
int n = sc.nextInt();
System.out.print("Enter number 1: ");
int max = sc.nextInt(); // seed max with the first value
for (int i = 2; i <= n; i++) {
System.out.print("Enter number " + i + ": ");
int val = sc.nextInt();
if (val > max) {
max = val;
}
}
System.out.println("Maximum: " + max);
Keep asking until the user provides acceptable input. This is the do-while pattern from Section 3, but worth calling out explicitly as its own pattern:
import java.util.Scanner;
Scanner sc = new Scanner(System.in);
int choice;
do {
System.out.println("Choose an option:");
System.out.println(" 1. Start");
System.out.println(" 2. Settings");
System.out.println(" 3. Quit");
System.out.print("Enter 1-3: ");
choice = sc.nextInt();
} while (choice < 1 || choice > 3);
System.out.println("You chose: " + choice);
These are the bugs that show up on nearly every intro Java exam. Know what they look like.
Looping one too many or one too few times. Usually a wrong comparison operator (< vs. <=).
// Prints 1 through 4 — MISSING 5
for (int i = 1; i < 5; i++) {
System.out.print(i + " ");
}
// Output: 1 2 3 4
// Prints 1 through 5 — CORRECT
for (int i = 1; i <= 5; i++) {
System.out.print(i + " ");
}
// Output: 1 2 3 4 5
Always ask: "Should the loop run when i equals the boundary value?" If yes, use <=. If no, use <.
int i = 0;
while (i < 5) {
System.out.println(i);
// BUG: i never changes — loops forever!
}
// Fix: add i++ inside the body
int i = 0;
while (i < 5) {
System.out.println(i);
i++; // now the condition eventually becomes false
}
// BUG: condition is false immediately — loop never runs
for (int i = 10; i < 1; i++) {
System.out.println(i);
}
// Fix: count down if starting high
for (int i = 10; i >= 1; i--) {
System.out.println(i);
}
// BUG: i is incremented by the header AND by the body
// Skips 1, 3, 5, 7, 9 — prints only 0, 2, 4, 6, 8
for (int i = 0; i < 10; i++) {
System.out.println(i);
i++; // accidental double increment
}
Java has a fourth loop syntax designed specifically for iterating over arrays and collections. It is called the enhanced for loop, or informally the for-each loop. You will use it extensively once we cover arrays in a later module — here's a quick preview.
for (dataType variableName : arrayOrCollection) {
// use variableName here
}
Read the colon as "in". So for (int score : scores) means "for each int named score in the scores array."
int[] scores = {85, 92, 78, 96, 88};
for (int score : scores) {
System.out.println("Score: " + score);
}
int[] scores = {85, 92, 78, 96, 88};
int total = 0;
for (int score : scores) {
total += score;
}
double average = (double) total / scores.length;
System.out.printf("Average: %.1f%n", average);
| Situation | Use |
|---|---|
| Just reading every element in order | Enhanced for (cleaner) |
Need the index value (i) | Regular for |
| Need to modify the array while iterating | Regular for |
| Iterating part of the array | Regular for |
The enhanced for loop is read-only from the array's perspective. If you do score = 100 inside the loop, you're changing the local variable score, not the actual array element. Use a regular indexed for loop when you need to update array values.
| Term | Definition |
|---|---|
| loop | A control structure that repeats a block of code zero or more times |
| iteration | One single pass through a loop body |
| pre-test loop | A loop that checks its condition before executing the body (while, for) |
| post-test loop | A loop that executes the body first, then checks the condition (do-while) |
| sentinel value | A special input value that signals "stop looping" |
| infinite loop | A loop whose condition never becomes false; program runs forever |
| accumulator | A variable that builds up a running total across iterations |
| nested loop | A loop placed inside another loop; inner body runs outer×inner total times |
| break | Statement that immediately exits the enclosing loop |
| continue | Statement that skips the rest of the current iteration and moves to the next |
| off-by-one error | A bug where a loop runs one too many or one too few times |
| enhanced for loop | The for-each syntax: for (type item : collection) — iterates over every element |
for when you need the index or need to modify elements.Name: _________________________________ Date: _____________ Score: _____ / 10
What type of loop is the while loop?
What is the output of the following code?
int x = 10;
while (x > 7) {
System.out.print(x + " ");
x--;
}
Which loop type guarantees the loop body executes at least once?
How many times does the body of the inner loop execute in total in this code?
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 3; j++) {
System.out.print("*");
}
}
What does the break statement do inside a loop?
What is the output of the following code?
for (int i = 1; i <= 6; i++) {
if (i % 3 == 0) {
continue;
}
System.out.print(i + " ");
}
Which of the following correctly describes an off-by-one error?
What is the output of the following code?
int total = 0;
for (int i = 1; i <= 4; i++) {
total += i;
}
System.out.println(total);
In an enhanced for loop (for-each), what happens if you assign a new value to the loop variable inside the body?
A programmer writes the following loop. What is the most likely bug?
int count = 0;
while (count < 5) {
System.out.println("Count: " + count);
}
| Question | Answer | Explanation |
|---|---|---|
| 1 | C | A for loop has three parts: initialization, condition, and update. |
| 2 | B | A while loop checks its condition before each iteration. |
| 3 | D | A do-while loop always executes at least once before checking the condition. |
| 4 | C | An infinite loop runs forever because the condition never becomes false. |
| 5 | D | break exits the loop immediately, skipping remaining iterations. |
| 6 | A | continue skips the rest of the current iteration and moves to the next. |
| 7 | A | A sentinel value signals the end of input in a loop. |
| 8 | B | Nested loops: the inner loop completes all iterations for each iteration of the outer loop. |
| 9 | C | The loop counter variable controls how many times the loop runs. |
| 10 | B | A for loop is preferred when the number of iterations is known in advance. |