while and do-while
A for loop is for a count the program knows before it starts. A while loop is for a count it does not: it tests a condition before every pass and stops when the condition is false, which may be never. The do-while form tests after the body, so the body always runs at least once.
while
The condition is a boolean expression, evaluated before the first pass and after every pass. Something in the body must move the program toward a false condition, or the loop never ends.
The file Countdown.java:
public class Countdown {
public static void main(String[] args) {
int n = 3;
while (n > 0) {
System.out.println(n);
n--;
}
System.out.println("liftoff");
}
}
javac -Xlint:all Countdown.java
java Countdown
3
2
1
liftoff
The condition is tested four times: true for 3, 2 and 1, then false for 0. The liftoff line is outside the loop, so it runs once, after the last pass.
do-while
do { ... } while (condition); runs the body and then tests. When the condition is false from the start, the body still ran once, which is the whole difference from while and the reason to choose it for a menu that has to be shown before it is answered.
public class DoWhile {
public static void main(String[] args) {
int n = 0;
while (n > 0) {
System.out.println("while body");
}
do {
System.out.println("do body");
n++;
} while (n < 3);
System.out.println("n: " + n);
}
}
javac -Xlint:all DoWhile.java
java DoWhile
do body
do body
do body
n: 3
The while body printed nothing because 0 is not greater than 0. The do body ran for n = 0, 1 and 2, and the loop ended when n reached 3, which is the value the last line prints.
A sentinel loop
A sentinel is a value the data uses to say stop, and the loop tests for it before it uses the element. The test comes first in the condition, so the guard against the end of the array and the guard against the sentinel are both in one &&, left to right.
public class Sentinel {
public static void main(String[] args) {
int[] values = {4, 8, 15, 16, -1, 23, 42};
int sum = 0;
int count = 0;
int index = 0;
while (index < values.length && values[index] != -1) {
sum += values[index];
count++;
index++;
}
System.out.println("count: " + count);
System.out.println("sum: " + sum);
}
}
javac -Xlint:all Sentinel.java
java Sentinel
count: 4
sum: 43
Four values are before the sentinel, and their sum is 43. The three values after it are never read, which is what a sentinel means: the rest of the data is not part of this run. The order of the two tests matters when the sentinel may be the last element, because values[index] would then be out of range.
A loop over input
Scanner reads tokens from a string, a file or standard input. hasNextInt asks whether the next token is an integer and nextInt consumes it, so the two together make a loop that ends at the first token that is not a number.
import java.util.Scanner;
public class ScannerInput {
public static void main(String[] args) {
Scanner scanner = new Scanner("3\n4\n5");
int total = 0;
while (scanner.hasNextInt()) {
total += scanner.nextInt();
}
System.out.println("total: " + total);
}
}
javac -Xlint:all ScannerInput.java
java ScannerInput
total: 12
The scanner is built over a string here so that the program is one file with no input to type. Over System.in the same loop reads what a person types, and hasNextInt becomes false at the end of the input. Lesson 104 takes the scanner apart, including the newline that nextInt leaves behind.
Exercises
- Change Countdown.java to count up from 1 to 3 with a while loop.
- Make the condition of the do-while in DoWhile.java false from the start. How many lines does the body print?
- Move the sentinel in Sentinel.java to the first position and predict the count and the sum.
- Change hasNextInt to hasNext in ScannerInput.java and read strings. What does the total become?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
When is the condition of a while loop tested?
Answer
Before the first pass and after every pass
A while tests before each pass, so a false condition means zero passes.
-
What does a do-while loop do that a while loop does not?
Answer
It runs the body at least once
The do-while tests after the body, so the first pass always happens.
-
What is a sentinel value?
Answer
A value that tells the loop to stop
The loop reads values until it meets the sentinel, which is not part of the data.
-
What does this program print?
public class Q1 { public static void main(String[] args) { int n = 3; while (n > 0) { System.out.println(n); n--; } } }Answer
3 / 2 / 1
The condition is false at 0, so the loop prints 3, 2 and 1 and stops.
-
What does this program print?
public class Q2 { public static void main(String[] args) { int n = 0; do { System.out.println("once"); n++; } while (n < 0); System.out.println(n); } }Answer
once / 1
The body runs before the first test, then n is 1 and the condition is false.
-
What does this program print?
public class Q3 { public static void main(String[] args) { int[] values = {4, 8, -1, 16}; int sum = 0; int index = 0; while (index < values.length && values[index] != -1) { sum += values[index]; index++; } System.out.println(sum); } }Answer
12
The loop stops at the sentinel -1, so only 4 and 8 are added.
-
What does this program print?
import java.util.Scanner; public class Q4 { public static void main(String[] args) { Scanner scanner = new Scanner("2 3 4"); int total = 0; while (scanner.hasNextInt()) { total += scanner.nextInt(); } System.out.println(total); } }Answer
9
The scanner reads three integers and the loop adds them.
-
What happens when a while condition never becomes false?
Answer
The loop runs until the program is stopped
A loop with no exit runs forever; break, a changed condition or an external stop is needed.
-
What does this program print?
public class Q5 { public static void main(String[] args) { int n = 1; int count = 0; while (n < 10) { n *= 2; count++; } System.out.println(n + " " + count); } }Answer
16 4
The values are 2, 4, 8 and 16, and the loop stops when n is no longer below 10.
-
Why does the sentinel test come after the array bounds test in
index < values.length && values[index] != -1?Answer
The second test would read past the end when index is at length
The and operator short-circuits, so the element is read only when the index is inside the array.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev