Sub topic 2
Repeat while a condition is true
A while loop repeats work for as long as a condition is true. It is useful when a program needs to keep going until something changes. For example, a program might keep asking for input until the user types a special word.
You should be familiar with Java variables, arithmetic, Boolean expressions, and if statements before starting this chapter. You will also need a Java development kit installed to run the examples.
A condition controls repetition
A loop is a way to repeat a group of statements. Each pass through that group is an iteration. The group of statements inside the loop is called the loop body.
A condition is a Boolean expression: an expression whose result is either true or false. A while loop tests its condition before it runs the body:
- Test the condition.
- If the condition is
true, run the body. - Return to the condition and test it again.
- If the condition is
false, leave the loop and continue with the next statement after it.
The loop does not decide in advance how many times to run. It makes that decision one test at a time.
This is different from an if statement. An if statement tests a condition and can run its body once. A while loop returns to its condition after the body and can run the body many times.
Write a counting loop
Here is a complete program. Save it in a file named Counter.java.
public class Counter {
public static void main(String[] args) {
int count = 0;
while (count < 3) {
System.out.println(count);
count++;
}
System.out.println("Done.");
}
}Compile and run it from the folder containing the file:
javac Counter.java
java CounterThe output is:
0
1
2
Done.Look at the parts of the loop:
int count = 0;creates a whole-number variable and gives it a starting value.whiletells Java to repeat while the condition is true.(count < 3)is the condition. It asks whethercountis less than3.- The braces
{and}surround the loop body. System.out.println(count);prints the current value.count++;adds1tocount. This is called an increment.System.out.println("Done.");is after the loop, so it runs when the loop has finished.
The condition goes inside parentheses. The opening brace comes after the condition, and the closing brace marks the end of the body.
Keep the two statements in the body indented, as shown. Indentation makes the program easier to read, though Java uses the braces to determine which statements are in the body.
Trace the loop
To trace a program is to follow its steps and keep track of its values. Tracing helps you see why a loop produces its output.
In Counter, the first condition test happens when count is 0.
| Condition test | Result | What the body does |
|---|---|---|
| `0 < 3` | `true` | Prints `0`, then changes `count` to `1` |
| `1 < 3` | `true` | Prints `1`, then changes `count` to `2` |
| `2 < 3` | `true` | Prints `2`, then changes `count` to `3` |
| `3 < 3` | `false` | Does not run; the program continues after the loop |
There are three iterations, but there are four condition tests. The final test is the one that tells Java to stop.
Notice that the body prints count before it increments it. On the first iteration, the program prints 0 and only then changes the value to 1. The order of statements inside a loop matters, just as it does outside a loop.
Also notice that the condition uses <, not <=. The expression count < 3 is false when count reaches 3. If you changed the condition to count <= 3, the loop would also print 3 before stopping.
A loop can run zero times
Because Java tests a while condition first, the body might not run at all.
In Counter.java, change the starting value from 0 to 3. Keep the condition as count < 3, then compile and run the program again.
The first test is now 3 < 3, which is false. Java skips the body, so the only output is:
Done.This is an important property of while: it repeats only when its condition is already true. It does not promise that the body will run even once.
Change the starting value back to 0 before trying the original program again.
Help the loop reach its end
For many loops, one part of the body changes a value that the condition uses. In the counting example, count++ changes count. Eventually, count < 3 becomes false, and the loop ends.
A loop that keeps running without reaching its end is an infinite loop. If you removed count++ from the original program, count would stay at 0. The condition count < 3 would stay true, so the program would keep printing 0.
For a loop that should finish, ask yourself:
- What must be true for the loop to run?
- What can change while the loop runs?
- How can that change make the condition false?
The answer does not always have to be a counter. A value might change because a user types something, because a calculation produces a new result, or because the program reads new information.
If you accidentally run a program that keeps printing, you can usually stop it by pressing Ctrl+C in the terminal. A terminal is a window where you type commands such as java Counter.
Repeat a calculation until a goal is reached
A counting loop is useful for learning the steps, but a while loop can also repeat a task until it reaches a goal.
Suppose you start with 10 dollars and add 7 dollars each time. You want to stop once you have at least 30 dollars. Save this program as Savings.java.
public class Savings {
public static void main(String[] args) {
int savings = 10;
int goal = 30;
while (savings < goal) {
savings = savings + 7;
System.out.println("Savings: " + savings);
}
System.out.println("Goal reached.");
}
}Compile and run it:
javac Savings.java
java SavingsThe output is:
Savings: 17
Savings: 24
Savings: 31
Goal reached.Before the first iteration, savings is 10 and goal is 30. The condition savings < goal is true, so the body adds 7 and prints the new amount.
The next two iterations raise the amount to 24 and then 31. When Java tests the condition again, 31 < 30 is false. The loop ends.
The condition does not say “stop exactly at 30.” It says to keep going while the amount is less than 30. Since each addition is 7, the amount can pass the goal. That is why the final amount is 31.
The condition is tested between iterations, not after each statement in the body. On the last iteration, the program adds 7 and prints 31 before it returns to the condition.
If the starting savings were already 30 or more, the loop body would not run. The program would go straight to printing Goal reached.
Use input to decide when to stop
A loop is especially useful when the program cannot know in advance how many times the body will run. In this example, the user chooses when to finish by typing stop.
A string is a sequence of characters, such as a word or a line of text. Java provides Scanner, a tool that can read text typed by the user. Save this program as RepeatLines.java.
import java.util.Scanner;
public class RepeatLines {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Type a line, or type stop to finish:");
String line = input.nextLine();
while (!line.equals("stop")) {
System.out.println("You typed: " + line);
System.out.println("Type a line, or type stop to finish:");
line = input.nextLine();
}
System.out.println("Finished.");
input.close();
}
}Compile and run it:
javac RepeatLines.java
java RepeatLinesHere is one possible run. The lines hello, Java, and stop are typed by the user.
Type a line, or type stop to finish:
hello
You typed: hello
Type a line, or type stop to finish:
Java
You typed: Java
Type a line, or type stop to finish:
stop
Finished.The import line makes Scanner available to the program. The statement new Scanner(System.in) creates a reader for text typed into the terminal. The call input.nextLine() waits for the user to enter a line and press Enter.
The program reads one line before it reaches the loop. It needs that first value so it can test the condition:
line.equals("stop")checks whether the text inlineis exactlystop.!means “not.” It reversestrueandfalse.- Therefore,
!line.equals("stop")is true when the line is notstop.
For strings, use equals to compare the text itself. The comparison is case-sensitive: Stop is not the same text as stop.
Inside the body, the program prints the line and then reads another one. That new line is stored in line. Java then returns to the condition and tests the new value.
If the user types stop at the first prompt, the condition is false on its first test. The body runs zero times, and the program prints Finished. Otherwise, it continues until the user types stop.
For this example, enter stop to finish normally. If the input ends before another line is available, nextLine() cannot read it and the program reports an error.
Read and write loop conditions carefully
A while condition must produce a Boolean value. These examples assume count is an int:
| Condition | Meaning |
|---|---|
| `count < 3` | `count` is less than `3` |
| `count <= 3` | `count` is less than or equal to `3` |
| `count == 3` | `count` is equal to `3` |
| `count != 3` | `count` is not equal to `3` |
Choose the condition to match the question you want the program to ask before each iteration.
For example, count < 3 becomes false when an increasing count reaches 3. The condition count != 3 also becomes false if the count reaches exactly 3. But if the count jumps from 2 to 4, it is still not equal to 3. The loop may continue longer than intended.
Pay attention to the difference between = and ==:
=assigns a value, as incount = 0.==compares values, as incount == 3.
The condition is checked at the top of every iteration. Changing a variable in the body does not make Java leave the body immediately. Java finishes the current body, then checks the condition again.
Practice tracing while loops
For each exercise, predict the result before reading the answer. If you are unsure, use the tracing method: write down the value at each condition test and follow the body in order.
Exercise
In the original Counter program, what prints if count starts at 1 instead of 0?
Show answer
The loop prints 1 and 2. The next test is 3 < 3, which is false, so the program then prints Done.
Exercise
In Savings, what happens if savings starts at 35 and goal stays at 30?
Show answer
The first test, 35 < 30, is false. The body runs zero times, so the program prints only Goal reached.
Exercise
A loop starts with count equal to 0, tests count < 4, and adds 2 to count in its body. What values does count have when the condition is tested, and when does the loop stop?
Show answer
The condition is tested with count at 0, 2, and 4. The first two tests are true. The test 4 < 4 is false, so the loop stops.