Java • Control Flow

While & Do-While Loops — Use while and do-while loops appropriately

Master the art of repeating code intelligently with condition-driven loops in Java.

Java programming emblem with a coffee cup, code braces, and terminal
Inside this lesson 10 sections 5 questions 9 figures

SECTION 1

Historical Context & Motivation

Computers are fundamentally about doing repetitive work fast—but early programmers had to figure out how to tell machines to repeat instructions. The concept of a loop became one of the most important ideas in all of programming. Before high-level languages like Java existed, programmers wrote goto statements in assembly language to jump backward in code and re-execute instructions. This worked, but it created tangled, hard-to-read programs that developers called spaghetti code.

1949 • Assembly Language Loops

Early programmers used goto and conditional branch instructions to repeat sections of machine code, creating the first loops.

1966 • Structured Programming Theorem

Böhm and Jacopini proved that any computable program can be written using just three structures: sequence, selection, and iteration (loops).

1972 • C Language Standardizes while

Dennis Ritchie's C language introduced the while and do-while loop syntax that Java would later adopt nearly unchanged.

1995 • Java Inherits Loop Syntax

Java, designed by James Gosling at Sun Microsystems, carried forward C's while and do-while loops as core control-flow tools.

Structured programming replaced messy goto jumps with clean loop constructs. The central question this lesson addresses is: when should you use a while loop versus a do-while loop, and how do you write each one correctly? Understanding the difference will help you write cleaner, more intentional code.

SECTION 2

Core Principles & Definitions

Both while and do-while loops repeat a block of code as long as a boolean condition evaluates to true. They differ in one critical way: when the condition gets checked. Grasping this distinction is the key to choosing the right loop for any situation.

1

While Loop (Pre-Test)

Checks the condition before each iteration. If the condition is false initially, the body executes zero times.
2

Do-While Loop (Post-Test)

Checks the condition after each iteration. The body always executes at least once, regardless of the condition.
3

Loop Variable

A variable that changes each iteration and eventually makes the condition false. Without updating it, you get an infinite loop.
4

Boolean Condition

An expression that evaluates to true or false. Common operators include <, >=, !=, and ==.
5

Infinite Loop

A loop whose condition never becomes false. The program runs forever (or until it crashes). This is the most common loop bug for beginners.
✦

KEY TAKEAWAY

Think of a while loop like checking the weather before you go outside—if it's storming, you stay in and never go out. A do-while loop is like going outside first and then checking the weather—you're already outside at least once no matter what.

SECTION 3

Visual Explanation — Loop Flowcharts

while Loopdo-while LoopStartconditiontrue?trueLoop BodyfalseEndStartLoop Bodyconditiontrue?truefalseEndCondition checked BEFORE bodyCondition checked AFTER body
The left flowchart shows a while loop: the diamond-shaped condition check comes before the loop body. The right flowchart shows a do-while loop: the body executes first, and the condition is checked after. Notice how the do-while always enters the body at least once.

Study the two flowcharts above carefully. In the left diagram (the while loop), the program hits the condition diamond first. If that condition is already false, the program takes the dashed path straight to "End" and the body never runs. In the right diagram (the do-while loop), the program enters the body immediately. Only after executing the body does the condition get evaluated. This is why a do-while loop always runs at least once.

SECTION 4

How While & Do-While Loops Work in Code

The while Loop Syntax

WHILE LOOP TEMPLATE

while(condition)//loopbody//updateloopvariablewhile (condition) { // loop body // update loop variable }

condition — a boolean expression evaluated before each iteration. loop body — the statements that repeat. update — code that changes the loop variable so the condition eventually becomes false.

Here is a concrete example that prints the numbers 1 through 5. The variable i starts at 1, and the loop continues as long as i <= 5. After printing, i++ increments i by 1 each time.

WHILE LOOP EXAMPLE

inti=1;while(i<=5)System.out.println(i);i++;//Output:12345int i = 1; while (i <= 5) { System.out.println(i); i++; } // Output: 1 2 3 4 5

When i reaches 6, the condition 6 <= 5 is false, so the loop terminates.

The do-while Loop Syntax

DO-WHILE LOOP TEMPLATE

do//loopbody//updateloopvariablewhile(condition);do { // loop body // update loop variable } while (condition);

Note the semicolon after the closing parenthesis — this is required and easy to forget! The body runs first, then the condition is checked.

DO-WHILE LOOP EXAMPLE

inti=1;doSystem.out.println(i);i++;while(i<=5);//Output:12345int i = 1; do { System.out.println(i); i++; } while (i <= 5); // Output: 1 2 3 4 5

This produces the same output as the while example. The difference appears when the condition is false from the start — the do-while body still runs once.

⚠

Watch Out: Infinite Loops!

If you forget to update the loop variable (like leaving out i++), the condition never becomes false and the loop runs forever. Your program will freeze. If this happens, press Ctrl + C in your terminal to stop it.

SECTION 5

Choosing While vs. Do-While

Knowing the syntax is only half the battle — you also need to know which loop to pick for a given situation. The decision comes down to one question: does the code inside the loop need to run at least once, regardless of the condition?

Decision Guide: Which Loop Should I Use?Need to repeat code?YesKnow exactcount?YesUse for loop(not this lesson)NoMust run atleast once?Nowhile loopwhile (cond) { ... }Yesdo-while loopdo { ... } while (cond);The key question: does the body NEED to execute before the first check?
This decision tree helps you choose the right loop. If you know the exact number of iterations, prefer a for loop (covered in another lesson). If the count is unknown and depends on a condition, ask whether the body must execute at least once. If yes, use do-while. If not necessarily, use while.

Common Use Cases

ScenarioBest LoopWhy
Reading from a file until end-of-filewhileThe file might be empty, so you should check before reading.
Waiting for valid user inputdo-whileYou need to ask the user at least once before you can check if input is valid.
Searching through a listwhileThe list could be empty; checking the condition first avoids errors.
Displaying a menu until the user quitsdo-whileYou need to show the menu at least once so the user can choose an option.
Counting down from a numberwhileIf the starting number is already 0, you don't want to print anything.

Common scenarios and which loop fits best

SECTION 6

Worked Example — Input Validation with do-while

Let's walk through a realistic example. Imagine you're building a program that asks the user to enter an exam score between 0 and 100. If they type something out of range, you ask again. Since you must ask at least once, this is a perfect situation for a do-while loop.

Exam Score Validator

  1. 1

    Step 1 — Declare Variables

    We need a Scanner object for input and an int to hold the score.
    Scanner scanner = new Scanner(System.in); and int score;
  2. 2

    Step 2 — Write the do-while Loop

    The loop body prompts the user and reads their input. The condition checks if the score is invalid (below 0 or above 100). If invalid, the loop repeats.
    do { System.out.print("Enter score (0-100): "); score = scanner.nextInt(); } while (score < 0 || score > 100);
  3. 3

    Step 3 — Trace Through an Example Run

    Suppose the user types -5 first. The body runs, score becomes −5. The condition -5 < 0 || -5 > 100 is true, so the loop repeats. The user then types 85. The condition 85 < 0 || 85 > 100 is false, so the loop exits.
    Final value: score = 85
  4. 4

    Step 4 — Use the Validated Score

    After the loop, we know score is guaranteed to be between 0 and 100 inclusive. We can safely use it.
    System.out.println("You entered: " + score);
💡

Why Not a while Loop Here?

If you used a while loop, you'd need to initialize score to an invalid value (like −1) just to make the condition true on the first check. That's a workaround—do-while is cleaner because the intent is clear: ask first, then validate.

SECTION 7

While vs. Do-While — Strengths & Limitations

Featurewhiledo-while
Condition checkBefore each iteration (pre-test)After each iteration (post-test)
Minimum executions0 times1 time
Semicolon after conditionNoYes — required after the closing parenthesis
ReadabilityCondition is visible at the top—easy to see the guardCondition is at the bottom—less immediately visible
Frequency in real codeVery common — the default choice for most loopsLess common — mainly for menus, input validation, and retry logic
Risk of infinite loopSame risk — must update loop variable in bodySame risk — must update loop variable in body

Side-by-side comparison of while and do-while loops

✦

KEY TAKEAWAY

In practice, while loops appear far more often in Java code than do-while loops. Think of while as your default tool—like a regular screwdriver. The do-while is a specialty tool—like a ratchet—that you reach for only when you specifically need the "run at least once" guarantee, such as input validation or menu display.

SECTION 8

Connecting to Advanced Concepts

Once you're comfortable with while and do-while, you'll encounter more advanced loop-related concepts in Java. Understanding the basics now prepares you to use tools like break, continue, nested loops, and even recursion later.

What You LearnedWhat Comes Next
while and do-while syntaxfor loops and enhanced for-each loops for collections
Using a boolean condition to control repetitionUsing break to exit a loop early and continue to skip an iteration
Single-level loopsNested loops (a loop inside a loop) for grids, tables, and multi-dimensional data
Iterative repetitionRecursion — a method calling itself to solve sub-problems
Looping with simple countersUsing Iterator objects and Stream API for advanced data processing

How while/do-while connects to future Java topics

The idea of condition-driven repetition is universal in programming. Whether you eventually learn Python, JavaScript, or any other language, you'll find equivalents to while loops everywhere. Mastering them in Java gives you a transferable skill that applies to virtually every programming language.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

What is the key difference between a while loop and a do-while loop? If a while loop's condition is false from the start, how many times does the body execute? What about a do-while loop in the same situation?
Show answer
The key difference is when the condition is evaluated. A while loop is a pre-test loop — it checks the condition before the body runs. If the condition starts as false, the body executes zero times. A do-while loop is a post-test loop — it runs the body first, then checks the condition. So even if the condition is false from the start, the body still executes exactly one time.

Question 2: BASIC CALCULATION

Trace through the following code and determine the final value of sum after the loop completes: int sum = 0; int n = 1; while (n <= 4) { sum += n; n++; }
Show answer
Let's trace each iteration. Initially, sum = 0 and n = 1. Iteration 1: n = 1 ≤ 4 is true, sum = 0 + 1 = 1, n becomes 2. Iteration 2: n = 2 ≤ 4 is true, sum = 1 + 2 = 3, n becomes 3. Iteration 3: n = 3 ≤ 4 is true, sum = 3 + 3 = 6, n becomes 4. Iteration 4: n = 4 ≤ 4 is true, sum = 6 + 4 = 10, n becomes 5. Now n = 5 ≤ 4 is false, so the loop ends. The final value of sum is 10 (the sum of 1 + 2 + 3 + 4).

Question 3: INTERMEDIATE

Write a do-while loop that generates random integers between 1 and 10 (inclusive) and prints each one. The loop should stop when it generates the number 7. Use (int)(Math.random() * 10) + 1 to generate random numbers. Explain why do-while is the correct choice here.
Show answer
Here's the solution: int num; do { num = (int)(Math.random() * 10) + 1; System.out.println(num); } while (num != 7); A do-while loop is the correct choice because you need to generate a number before you can check whether it equals 7. You can't evaluate the condition without first producing a value. The body must run at least once to create the first random number.

Question 4: APPLIED

A bank account starts with a balance of $1,000. Each year, the bank charges a $50 annual fee. Write a while loop that determines how many years it takes for the balance to reach $0 or below. Print the number of years. Then explain: what would happen if you used a do-while loop instead, and would the result change?
Show answer
Solution: int balance = 1000; int years = 0; while (balance > 0) { balance -= 50; years++; } System.out.println(years); After 20 iterations, balance reaches exactly $0 (which is not > 0), so the loop stops and prints 20. If you used a do-while loop with the same condition, the result would be the same because the initial condition (1000 > 0) is true, so both loops enter the body on the first pass. The difference would only appear if the starting balance were already $0 or negative — then the while loop would print 0, but the do-while would subtract $50 once and print 1.

Question 5: CRITICAL THINKING

Consider this code: int x = 10; while (x > 0) { System.out.println(x); x -= 3; } First, trace through the loop and list all values printed. Then answer: could you rewrite this as a do-while loop and get the same output? Now suppose x started at 0 — would both versions still produce the same output? Justify your answer.
Show answer
Tracing with x = 10: Iteration 1 prints 10, x becomes 7. Iteration 2 prints 7, x becomes 4. Iteration 3 prints 4, x becomes 1. Iteration 4 prints 1, x becomes −2. Now −2 > 0 is false, so the loop stops. Output: 10, 7, 4, 1. Yes, you could rewrite this as do { System.out.println(x); x -= 3; } while (x > 0); and get the same output because when x starts at 10, the condition is true initially, so both loops behave identically. However, if x started at 0, the while loop would print nothing (0 > 0 is false immediately), but the do-while loop would print 0 once before checking the condition. This demonstrates the fundamental difference: do-while always guarantees at least one execution.

SUMMARY

Lesson Summary

Summary

Java provides two condition-driven loop constructs. The while loop is a pre-test loop that evaluates its boolean condition before each iteration — if the condition is false from the start, the body executes zero times. The do-while loop is a post-test loop that runs the body first and then checks the condition — guaranteeing at least one execution. Remember that do-while requires a semicolon after its closing parenthesis.

Use while as your default loop when repetition depends on a condition and the body might not need to run. Use do-while specifically when you need the body to execute before the first condition check, such as input validation or menu displays. Always include a loop variable update in the body to avoid infinite loops, and choose the right loop by asking: "Must this code run at least once?"

Varsity Tutors • Java • While & Do-While Loops