Java while and do-while Loops with Examples
Introduction
The for loopClick to read tutorial: Java for Loop Tutorial with Examples is ideal when you know in advance how many times to repeat. Often you do not - keep asking until the user types a valid answer, keep reading until the input ends, keep halving a number until it reaches 1. For these cases Java has the while and do-while loops. This tutorial explains Java's while and do-while loops with examples. We will start with the while loop and how it runs. We will then use it for loops whose number of repetitions is not known in advance. Next we will look at the do-while loop, which always runs at least once, and compare the two. Lastly, we will deal with infinite loops - the deliberate kind, and the accidental kind.
The while loop Syntax of the while loop
Where,
OUTPUT of the above code
Unlike a for loop's counter,
When the number of repetitions is unknown
A while loop shines when the loop stops because of a result, not a count. Each example below repeats a different, unknown number of times.
OUTPUT of the above code
Explanation of the code
The do-while loop checks its condition after each iteration, so the body always runs at least once. Note the semicolon after the condition - it is required. This makes do-while the natural choice for menus and input prompts, which must be shown at least once before there is anything to check.
OUTPUT of the above code
The menu was shown, the user's choice was handled, and the condition
while vs do-while
The only difference is when the condition is checked. When the condition is
OUTPUT of the above code
OUTPUT of the above code
Accidental infinite loops are a common bug. Typical causes are -
The while loop Syntax of the while loop
while (condition) { body }conditionis abooleanexpression, checked before each iteration.- While the condition is
true, the body runs again and again. As soon as it isfalse, the loop ends. - If the condition is
falsethe first time, the body never runs.
false, or the loop never ends.
A simple while loop
//WhileCountdown.java
public class WhileCountdown {
public static void main(String[] args) {
int count = 3;
while (count > 0) {
System.out.println("count = " + count);
count--;
}
System.out.println("Done, count = " + count);
}
}
count = 3 count = 2 count = 1 Done, count = 0
count is declared before the loop, so it still exists afterwards and holds its final value, 0.
while loops that repeat an unknown number of times
//WhileExamples.java
public class WhileExamples {
public static void main(String[] args) {
// How many digits does a number have?
int number = 4096;
int digits = 0;
int n = number;
while (n > 0) {
n /= 10;
digits++;
}
System.out.println(number + " has " + digits + " digits");
// How many years until savings double at 7% interest?
double balance = 1000;
int years = 0;
while (balance < 2000) {
balance *= 1.07;
years++;
}
System.out.printf("Savings double after %d years (%.2f)%n", years, balance);
// Greatest common divisor - Euclid's algorithm
int a = 84, b = 36;
while (b != 0) {
int remainder = a % b;
a = b;
b = remainder;
}
System.out.println("GCD of 84 and 36 = " + a);
// Collatz sequence: halve if even, 3n + 1 if odd, until 1
int c = 6;
System.out.print("Collatz from 6: " + c);
while (c != 1) {
c = (c % 2 == 0) ? c / 2 : 3 * c + 1;
System.out.print(" -> " + c);
}
System.out.println();
}
}
4096 has 4 digits Savings double after 11 years (2104.85) GCD of 84 and 36 = 12 Collatz from 6: 6 -> 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
- The digit counter divides by 10 until nothing is left - 4096, 409, 40, 4, 0 - counting four steps.
- The savings loop multiplies by 1.07 each year until the balance reaches 2000.
- Euclid's algorithm repeatedly replaces
(a, b)with(b, a % b)untilbis 0;ais then the greatest common divisor. - None of these loops could easily be written with a fixed count - the condition is what ends them.
do { body } while (condition);A menu with a do-while loop
//MenuLoop.java
import java.util.Scanner;
public class MenuLoop {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int balance = 100;
int choice;
do {
System.out.println("1. Show balance 2. Deposit 50 3. Exit");
System.out.print("Choose: ");
choice = scanner.nextInt();
if (choice == 1) {
System.out.println("Balance: " + balance);
} else if (choice == 2) {
balance += 50;
System.out.println("Deposited 50");
}
} while (choice != 3);
System.out.println("Goodbye! Final balance: " + balance);
}
}
1. Show balance 2. Deposit 50 3. Exit Choose: 1 Balance: 100 1. Show balance 2. Deposit 50 3. Exit Choose: 2 Deposited 50 1. Show balance 2. Deposit 50 3. Exit Choose: 1 Balance: 150 1. Show balance 2. Deposit 50 3. Exit Choose: 3 Goodbye! Final balance: 150
choice != 3 was checked only at the end of each round. User input is covered in Reading User Input with ScannerClick to read tutorial: Reading User Input in Java with Scanner.
false from the start, a while loop runs zero times, but a do-while loop still runs once -
while and do-while with a condition that is false from the start
//WhileVsDoWhile.java
public class WhileVsDoWhile {
public static void main(String[] args) {
int x = 10;
while (x < 5) {
System.out.println("while body ran");
}
do {
System.out.println("do-while body ran, although x < 5 is " + (x < 5));
} while (x < 5);
}
}
do-while body ran, although x < 5 is false
- Use for when the number of iterations is known, or you are stepping through a range or an array.
- Use while when the loop may need to run zero times, and stops on a condition.
- Use do-while when the body must run at least once - menus, prompts, and "try, then check" logic.
false is an infinite loop. Sometimes this is deliberate: servers and games often run while (true), and leave the loop with break or return when a stop condition occurs -
A deliberate infinite loop with break
//WhileTrue.java
public class WhileTrue {
public static void main(String[] args) {
int attempt = 0;
while (true) {
attempt++;
int roll = (attempt * 7) % 6 + 1; // a stand-in for a dice roll
System.out.println("Attempt " + attempt + ": rolled " + roll);
if (roll == 6) {
break;
}
}
System.out.println("Got a 6 after " + attempt + " attempts");
}
}
Attempt 1: rolled 2 Attempt 2: rolled 3 Attempt 3: rolled 4 Attempt 4: rolled 5 Attempt 5: rolled 6 Got a 6 after 5 attempts
- Forgetting to update the variable in the condition - for example, leaving out
count--in the countdown above. - Updating in the wrong direction -
count++instead ofcount--. - A semicolon after the condition -
while (count > 0);repeats an empty statement forever, because the block after it is not part of the loop. - Comparing floating-point values with != -
while (x != 1.0)may never be exactly true because of rounding. Use<or>instead.
Ctrl+C in the terminal (or the stop button in your IDE) to end it, then check the loop condition.
Summary
In this tutorial we first used the while loop, which checks its condition before each iteration and may run zero times. We then wrote while loops whose number of repetitions is not known in advance - counting digits, doubling savings, Euclid's algorithm and the Collatz sequence. Next we used the do-while loop, which checks its condition at the end and always runs at least once, to build a menu. We then compared while, do-while and for, and when to use each. Lastly, we wrote a deliberate infinite loop with break, and went through the causes of accidental ones. In the next tutorial, we will look at the simplest way to go through arrays and collections - the enhanced for loopClick to read tutorial: Java Enhanced for Loop (for-each) with Examples.Java Fundamentals Tutorials
Java for Loop Tutorial with ExamplesClick to read tutorial: Java for Loop Tutorial with Examples Java Enhanced for Loop (for-each) with ExamplesClick to read tutorial: Java Enhanced for Loop (for-each) with Examples Java if, else if and else Statements with ExamplesClick to read tutorial: Java if, else if and else Statements with Examples Java switch Statement Tutorial with ExamplesClick to read tutorial: Java switch Statement Tutorial with Examples Java Switch Expressions: Arrow Labels and yieldClick to read tutorial: Java Switch Expressions: Arrow Labels and yield Java break, continue and Labeled Loops ExplainedClick to read tutorial: Java break, continue and Labeled Loops Explained What is Java? History, Features, Editions and UsesClick to read tutorial: What is Java? History, Features, Editions and Uses
Java for Loop Tutorial with ExamplesClick to read tutorial: Java for Loop Tutorial with Examples Java Enhanced for Loop (for-each) with ExamplesClick to read tutorial: Java Enhanced for Loop (for-each) with Examples Java if, else if and else Statements with ExamplesClick to read tutorial: Java if, else if and else Statements with Examples Java switch Statement Tutorial with ExamplesClick to read tutorial: Java switch Statement Tutorial with Examples Java Switch Expressions: Arrow Labels and yieldClick to read tutorial: Java Switch Expressions: Arrow Labels and yield Java break, continue and Labeled Loops ExplainedClick to read tutorial: Java break, continue and Labeled Loops Explained What is Java? History, Features, Editions and UsesClick to read tutorial: What is Java? History, Features, Editions and Uses