← Back to Core Java Course | Chapter 4: Control Flow | Lesson 6 of 9

Java do-while Loop

Basic do-while Loop

A do-while loop runs its body first and only checks the condition afterward, at the bottom -- the opposite order from a regular while loop, which tests the condition before ever entering the body.

Example: Basic do-while Loop

java
public class Main {
	public static void main(String[] args) {
		int i = 0;
		do {
			System.out.println(i);
			i++;
		} while (i < 3);
	}
}

Guaranteeing One Run

This ordering guarantees the loop body executes at least once even if the condition would have been false from the very start, which a standard while loop can never guarantee.

Example: Guaranteeing One Run

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

Incrementing Variables inside Loop

You must modify the variable checked in your loop condition somewhere inside the do-while block, or the loop keeps repeating forever since the condition never has a chance to become false.

Example: Incrementing Variables inside Loop

java
public class Main {
	public static void main(String[] args) {
		int i = 0;
		do {
			System.out.println(i);
			i++; // without this, the loop never ends
		} while (i < 3);
	}
}

Simulated Interactive Runs

Just like any loop, you must update the variable the condition depends on somewhere inside the do-while body -- if that variable never changes, the loop will run forever once it starts.

Example: Simulated Interactive Runs

java
public class Main {
	public static void main(String[] args) {
		int attempts = 0;
		do {
			attempts++;
			System.out.println("Attempt " + attempts);
		} while (attempts < 3);
	}
}

Nested do-while Loops

Nesting a do-while inside another do-while lets you build structures like a grid where each outer iteration always processes at least one full pass of the inner loop, guaranteed.

Example: Nested do-while Loops

java
public class Main {
	public static void main(String[] args) {
		int row = 1;
		do {
			int col = 1;
			do {
				System.out.print(col + " ");
				col++;
			} while (col <= 3);
			System.out.println();
			row++;
		} while (row <= 2);
	}
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.