3.8. Control Flow
Java, like any programming language, supports both conditional statements and loops to determine control flow. I will start with the conditional statements, then move on to loops, to end with a thorough discussion of the four forms of switch.
3.8.1. Block Scope
Before learning about control structures, you need to know more about blocks.
A block, or compound statement, consists of a number of Java statements, surrounded by a pair of braces. Blocks define the scope of your variables. A block can be nested inside another block. Here is a block that is nested inside the block of the main method:
void main() {
int n;
. . .
{
int k;
. . .
} // k is only defined up to here
}
You may not declare identically named local variables in two nested blocks. For example, the following is an error and will not compile:
void main() {
int n;
. . .
{
int k;
int n; // ERROR--can't redeclare n in inner block
. . .
}
}
3.8.2. Conditional Statements
The conditional statement in Java has the form
if (condition) statement
The condition must be surrounded by parentheses.
In Java, as in most programming languages, you will often want to execute multiple statements when a single condition is true. In this case, use a block statement that takes the form
{
statement1
statement2
. . .
}
For example:
if (yourSales >= target) {
performance = "Satisfactory";
bonus = 100;
}
In this code all the statements surrounded by the braces will be executed when yourSales is greater than or equal to target (see Figure 3.7).
Figure 3.7: Flowchart for the if statement
The more general conditional in Java looks like this (see Figure 3.8):
if (condition) statement1 else statement2
Figure 3.8: Flowchart for the if/else statement
For example:
if (yourSales >= target) {
performance = "Satisfactory";
bonus = 100 + 0.01 * (yourSales - target);
}
else {
performance = "Unsatisfactory";
bonus = 0;
}
The else part is always optional. An else groups with the closest if. Thus, in the statement
if (x <= 0) if (x == 0) sign = 0; else sign = -1;
the else belongs to the second if. Of course, it is a good idea to use braces to clarify this code:
if (x <= 0) { if (x == 0) sign = 0; else sign = -1; }
Repeated if . . . else if . . . alternatives are common (see Figure 3.9). For example:
if (yourSales >= 2 * target) {
performance = "Excellent";
bonus = 1000;
}
else if (yourSales >= 1.5 * target) {
performance = "Fine";
bonus = 500;
}
else if (yourSales >= target) {
performance = "Satisfactory";
bonus = 100;
}
else {
IO.println("You're fired");
}
Figure 3.9: Flowchart for the if/else if (multiple branches)
3.8.3. Loops
The while loop executes a statement (which may be a block statement) while a condition is true. The general form is
while (condition) statement
The while loop will never execute if the condition is false at the outset (see Figure 3.10).
Figure 3.10: Flowchart for the while statement
The program in Listing 3.3 determines how long it will take to save a specific amount of money for your well-earned retirement, assuming you deposit the same amount of money per year and the money earns a specified interest rate.
In the example, we are incrementing a counter and updating the amount currently accumulated in the body of the loop until the total exceeds the targeted amount.
while (balance < goal) {
balance += payment;
double interest = balance * interestRate / 100;
balance += interest;
years++;
}
IO.println(years + " years.");
(Don’t rely on this program to plan for your retirement. It lacks a few niceties such as inflation and your life expectancy.)
A while loop tests at the top. Therefore, the code in the block might never be executed. If you want to make sure a block is executed at least once, you need to move the test to the bottom, using the do/while loop. Its syntax looks like this:
do statement while (condition);
This loop executes the statement (which is typically a block) and only then tests the condition. If it’s true, it repeats the statement and retests the condition, and so on. The code in Listing 3.4 computes the new balance in your retirement account and then asks if you are ready to retire:
do {
balance += payment;
double interest = balance * interestRate / 100;
balance += interest;
years++;
// print current balance
. . .
// ask if ready to retire and get input
. . .
} while (input.equals("N"));
As long as the user answers "N", the loop is repeated (see Figure 3.11). This program is a good example of a loop that needs to be entered at least once, because the user needs to see the balance before deciding whether it is sufficient for retirement.
Figure 3.11: Flowchart for the do/while statement
Listing 3.3 Retirement.java
/**
* This program demonstrates a <code>while</code> loop.
*/
void main() {
// read inputs
double goal = Double.parseDouble(IO.readln("How much money do you need to retire? "));
double payment
= Double.parseDouble(IO.readln("How much money will you contribute every year? "));
double interestRate = Double.parseDouble(IO.readln("Interest rate in %: "));
double balance = 0;
int years = 0;
// update account balance while goal isn't reached
while (balance < goal) {
// add this year's payment and interest
balance += payment;
double interest = balance * interestRate / 100;
balance += interest;
years++;
}
IO.println("You can retire in " + years + " years.");
}
Listing 3.4 Retirement2.java
/**
* This program demonstrates a <code>do/while</code> loop.
*/
void main() {
double payment = Double.parseDouble(
IO.readln("How much money will you contribute every year? "));
double interestRate = Double.parseDouble(IO.readln("Interest rate in %: "));
double balance = 0;
int year = 0;
String input;
// update account balance while user isn't ready to retire
do {
// add this year's payment and interest
balance += payment;
double interest = balance * interestRate / 100;
balance += interest;
year++;
// print current balance
IO.println("After year %d, your balance is %,.2f".formatted(year,
balance));
// ask if ready to retire and get input
input = IO.readln("Ready to retire? (Y/N) ");
}
while (input.equals("N"));
}
3.8.4. Determinate Loops
The for loop is a general construct to support iteration controlled by a counter or similar variable that is updated after every iteration. As Figure 3.12 shows, the following loop prints the numbers from 1 to 10 on the screen:
for (int i = 1; i <= 10; i++)
IO.println(i);
The first slot of the for statement usually holds the counter initialization. The second slot gives the condition that will be tested before each new pass through the loop, and the third slot specifies how to update the counter.
Figure 3.12: Flowchart for the for statement
Although Java, like C++, allows almost any expression in the various slots of a for loop, it is an unwritten rule of good taste that the three slots should only initialize, test, and update the same counter variable. One can write very obscure loops by disregarding this rule.
Even within the bounds of good taste, much is possible. For example, you can have loops that count down:
for (int i = 10; i > 0; i--)
IO.println("Counting down . . . " + i);
IO.println("Blastoff!");
When you declare a variable in the first slot of the for statement, the scope of that variable extends until the end of the body of the for loop.
for (int i = 1; i <= 10; i++) {
. . .
}
// i no longer defined here
In particular, if you define a variable inside a for statement, you cannot use its value outside the loop. Therefore, if you wish to use the final value of a loop counter outside the for loop, be sure to declare it outside the loop header.
int i;
for (i = 1; i <= 10; i++) {
. . .
}
// i is still defined here
On the other hand, you can define variables with the same name in separate for loops:
for (int i = 1; i <= 10; i++) {
. . .
}
. . .
for (int i = 11; i <= 20; i++) { // OK to define another variable named i
. . .
}
A for loop is merely a convenient shortcut for a while loop. For example,
for (i = 10; i > 0; i--)
IO.println("Counting down . . . " + i);
can be rewritten as follows:
i = 10;
while (i > 0) {
IO.println("Counting down . . . " + i);
i--;
}
The first slot of a for loop can declare multiple variables, provided they are of the same type. And the third slot can contain multiple comma-separated expressions:
for (int i = 1, j = 10; i <= 10; i++, j--) { . . . }
While technically legal, this stretches the intuitive meaning of the for loop, and you should consider a while loop instead.
Listing 3.5 shows a typical example of a for loop.
The program computes the odds of winning a lottery. For example, if you must pick six numbers from the numbers 1 to 50 to win, then there are (50 × 49 × 48 × 47 × 46 × 45)/(1 × 2 × 3 × 4 × 5 × 6) possible outcomes, so your chance is 1 in 15,890,700. Good luck!
In general, if you pick k numbers out of n, there are
possible outcomes. The following for loop computes this value:
int lotteryOdds = 1;
for (int i = 1; i <= k; i++)
lotteryOdds = lotteryOdds * (n - i + 1) / i;
Listing 3.5 LotteryOdds.java
/**
* This program demonstrates a <code>for</code> loop.
*/
void main() {
int k = Integer.parseInt(IO.readln("How many numbers do you need to draw? "));
int n = Integer.parseInt(IO.readln("What is the highest number you can draw? "));
// Binomial coefficient n*(n-1)*(n-2)*...*(n-k+1)/(1*2*3*...*k)
int lotteryOdds = 1;
for (int i = 1; i <= k; i++)
lotteryOdds = lotteryOdds * (n - i + 1) / i;
IO.println("Your odds are 1 in " + lotteryOdds + ". Good luck!");
}3.8.5. Multiple Selections with switch
The if/else construct can be cumbersome when you have to deal with multiple alternatives for the same expression. The switch statement makes this easier, particularly with the form that has been introduced in Java 14.
For example, if you set up a menu system with four alternatives like that in Figure 3.13, you could use code that looks like this:
int choice = Integer.parseInt(IO.readln("Select an option (1, 2, 3, 4) "));
switch (choice) {
case 1 ->
. . .
case 2 ->
. . .
case 3 ->
. . .
case 4 ->
. . .
default ->
IO.println("Bad input");
}
Figure 3.13: Flowchart for the switch statement
Note the similarity to the switch expressions that you saw in Section 3.5.9. Unlike a switch expression, a switch statement has no value. Each case carries out an action.
The “classic” form of the switch statement, which dates all the way back to the C language, has been supported since Java 1.0. It has the form:
int choice = . . .;
switch (choice) {
case 1:
. . .
break;
case 2:
. . .
break;
case 3:
. . .
break;
case 4:
. . .
break;
default:
IO.println("Bad input");
}
Execution starts at the case label that matches the value on which the selection is performed and continues until the next break or the end of the switch. If none of the case labels match, then the default clause is executed, if it is present.
For symmetry, Java 14 also introduced a switch expression with fallthrough, for a total of four forms of switch. Table 3.7 shows them all.
Table 3.7: The four forms of switch
| Expression | Statement | |
|---|---|---|
| No Fallthrough |
int numLetters = switch (seasonName) {
case "Spring" -> {
IO.println("spring time!");
yield 6;
}
case "Summer", "Winter" -> 6;
case "Fall" -> 4;
default -> -1;
}; |
switch (seasonName) {
case "Spring" -> {
IO.println("spring time!");
numLetters = 6;
}
case "Summer", "Winter" ->
numLetters = 6;
case "Fall" ->
numLetters = 4;
default ->
numLetters = -1;
} |
| Fallthrough |
int numLetters = switch (seasonName) {
case "Spring":
IO.println("spring time!");
case "Summer", "Winter":
yield 6;
case "Fall":
yield 4;
default:
yield -1;
}; |
switch (seasonName) {
case "Spring":
IO.println("spring time!");
case "Summer", "Winter":
numLetters = 6;
break;
case "Fall":
numLetters = 4;
break;
default:
numLetters = -1;
} |
In the fallthrough variants, each case ends with a colon. If the cases end with arrows ->, then there is no fallthrough. You can’t mix colons and arrows in a single switch statement.
Each branch of a switch expression must yield a value. Most commonly, each value follows an -> arrow:
case "Summer", "Winter" -> 6;
If you cannot compute the result in a single expression, use braces and a yield statement. Like break, it terminates execution. Unlike break, it also yields a value—the value of the expression:
case "Spring" -> {
IO.println("spring time!");
yield 6;
}
With so many variations of switch, which one should you choose?
Avoid the fallthrough forms. It is very uncommon to need fallthrough.
Prefer switch expressions over statements.
For example, consider:
switch (seasonName) {
case "Spring", "Summer", "Winter":
numLetters = 6;
break;
case "Fall":
numLetters = 4;
break;
default:
numLetters = -1;
}
Since every case ends with a break, there is no need to use the fallthrough form. The following is an improvement:
switch (seasonName) {
case "Spring", "Summer", "Winter" ->
numLetters = 6;
case "Fall" ->
numLetters = 4;
default ->
numLetters = -1;
}
Now note that each branch assigns a value to the same variable. It is much more elegant to use a switch expression here:
numLetters = switch (seasonName) {
case "Spring", "Summer", "Winter" -> 6
case "Fall" -> 4
default -> -1
};
3.8.6. Statements That Break Control Flow
Although the designers of Java kept goto as a keyword, they decided not to include it in the language. In general, goto statements are considered poor style. Some programmers feel the anti-goto forces have gone too far (see, for example, the famous article of Donald Knuth called “Structured Programming with goto statements”). They argue that unrestricted use of goto is error-prone but that an occasional jump out of a loop is beneficial. The Java designers agreed and even added a new statement, the labeled break, to support this programming style.
Let us first look at the unlabeled break statement. The same break statement that you use to exit a switch statement can also be used to break out of a loop. For example:
while (years <= 100) {
balance += payment;
double interest = balance * interestRate / 100;
balance += interest;
if (balance >= goal) break;
years++;
}
Now the loop is exited if either years > 100 occurs at the top of the loop or balance >= goal occurs in the middle of the loop. Of course, you could have computed the same value for years without a break, like this:
while (years <= 100 && balance < goal) {
balance += payment;
double interest = balance * interestRate / 100;
balance += interest;
if (balance < goal) years++;
}
But note that the test balance < goal is repeated twice in this version. To avoid this repeated test, some programmers prefer the break statement.
The labeled break statement lets you break out of multiple nested loops. Occasionally something weird happens inside a deeply nested loop. In that case, you may want to break completely out of all the nested loops. It is inconvenient to program that simply by adding extra conditions to the various loop tests.
Here’s an example that shows the labeled break statement at work. Notice that the label must precede the outermost loop out of which you want to break. It also must be followed by a colon.
int n;
read_data:
while (. . .) { // this loop statement is tagged with the label
. . .
for (. . .) { // this inner loop is not labeled
IO.print();
n = Integer.parseInt(IO.readln("Enter a number >= 0: "));
if (n < 0) { // should never happen—can't go on
break read_data; // break out of read_data loop
}
. . .
}
}
// this statement is executed immediately after the labeled break
if (n < 0) { // check for bad situation
// deal with bad situation
}
else {
// carry out normal processing
}
If there is a bad input, the labeled break moves past the end of the labeled block. As with any use of the break statement, you then need to test whether the loop exited normally or as a result of a break.
Finally, there is a continue statement that, like the break statement, breaks the regular flow of control. The continue statement transfers control to the header of the innermost enclosing loop. Here is an example:
while (sum < goal) {
n = Integer.parseInt(IO.readln("Enter a number: "));
if (n < 0) continue;
sum += n; // not executed if n < 0
}
If n < 0, then the continue statement jumps immediately to the loop header, skipping the remainder of the current iteration.
If the continue statement is used in a for loop, it jumps to the “update” part of the for loop. For example:
for (count = 1; count <= 100; count++) {
n = Integer.parseInt(IO.readln("Enter a number, -1 to quit: "));
if (n < 0) continue;
sum += n; // not executed if n < 0
}
If n < 0, then the continue statement jumps to the count++ statement.
There is also a labeled form of the continue statement that jumps to the header of the loop with the matching label.
