AI Hints
Home›Java Tutorial›while Loops, do while and for Loops
Java · Lesson 38 of 120

do while

Run at least once.

⏱ 2 min read▶ Video at 48:43🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

A do while loop checks its condition at the end, not the start. So its body always runs at least once.

  • Check at the end
  • Body runs first
  • At least once

Asking until it is right

Do runs the body first. It asks for a guess. Then while checks the condition, at the bottom. If the guess isn't seven, it asks again. Notice the semicolon after the while. Run it. The user guessed three, then nine, then seven.

Main.javajava
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int guess;
        do {
            System.out.print("Guess the number (1-10): ");
            guess = in.nextInt();
        } while (guess != 7);
        System.out.println("Yes! It was 7.");
    }
}
Input typed: 3 · 9 · 7
Output
Guess the number (1-10): 3
Guess the number (1-10): 9
Guess the number (1-10): 7
Yes! It was 7.

The difference

N is ten, so n less than five is false, from the start. The while loop checks first, so its body never runs. The do while runs once, before checking. Run it. Only the do while line prints.

Main.javajava
public class Main {
    public static void main(String[] args) {
        int n = 10;
        while (n < 5) {
            System.out.println("while: " + n);
        }
        do {
            System.out.println("do while: " + n);
        } while (n < 5);
    }
}
Output
do while: 10

while or do while

Use while when the body might not need to run at all. Use do while when it must run at least once, like asking for input, and repeating until it's valid.

while

  • Checks firstMay run zero timesMost common

do while

  • Checks lastRuns at least onceGreat for input

Summary

A do while loop runs its body first, then checks the condition. So it always runs at least once. Next, the for loop.

Key takeaways
  • do { } while (c);
  • At least once
  • Good for input
Next up: for Loops — counting loops