Control Flow in Java

Java, like any programming language, supports both conditional statements and loops to determine control flow. We will start with the conditional statements, then move on to loops, to end with the somewhat cumbersome switch statement that you can use to test for many values of a single expression.

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:

public static void main(String[] args)

{

int n;

{

int k;

} // k is only defined up to here

}

You may not declare identically named variables in two nested blocks. For example, the following is an error and will not compile:

public static void main(String[] args)

{

int n;

{

int k;

int n; // ERROR–can t redefine n in inner block

}

}

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

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;

Figure 3.8 Flowchart for the if/else statement

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

{

System.out.println(“You’re fired”);

}

Figure 3.9 Flowchart for the if/else if (multiple branches)

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++;

}

System.out.println(years + ” years.”);

(Don’t rely on this program to plan for your retirement. We left out 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;

year++;

// 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.

Listing 3.3 Retirement/Retirement.java

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++)

System.out.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–)

System.out.printtn(“Counting down . . .” + i);

System.out.printtn(“Btastoff!”);

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 (int i = 10; i > 0; i–)

System.out.println(“Counting down . . . ” + i);

can be rewritten as

int i = 10; while (i > 0)

{

System.out.println(“Counting down . . . ” + i);

i–;

}

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 x 49 x 48 x 47 x 46 x 45)/(1 x 2 x 3 x 4 x 5 x 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;

5. Multiple Selections-The switch Statement

The if/else construct can be cumbersome when you have to deal with multiple selections with many alternatives. Java has a switch statement that is exactly like the switch statement in C and C++, warts and all.

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:

Scanner in = new Scanner(System.in);

System.out.print(“Select an option (1, 2, 3, 4) “);

int choice = in.nextInt();

switch (choice)

{

case 1:

break; case 2:

break; case 3:

break; case 4:

break;

default:

// bad input

break;

}

Figure 3.13 Flowchart for the switch statement

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.

A case label can be

  • A constant expression of type char, byte, short, or int
  • An enumerated constant
  • Starting with Java 7, a string literal

For example,

String input = . . .;

switch (input.toLowerCase())

{

case “yes”: // OK since Java 7

. . .

break;

. . .

}

When you use the switch statement with enumerated constants, you need not supply the name of the enumeration in each label—it is deduced from the
switch value. For example:

Size sz = . . .;

switch (sz)

{

case SMALL: // no need to use Size.SMALL

. . .

break;

. . .

} 

6. Statements That Break Control Flow

Although the designers of Java kept goto as a reserved word, 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 can also be used to break out of a loop. For example:

white (years <= 100)

{

balance += payment;

doubte interest = batance * interestRate / 100;

batance += interest; if (balance >= goal) break;

years++;

}

Now the loop is exited if either years > 100 occurs at the top of the loop or batance >= goat 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)

{

batance += payment;

double interest = balance * interestRate / 100;

batance += interest;

if (batance < goat)

years++;

}

But note that the test batance < goat is repeated twice in this version. To avoid this repeated test, some programmers prefer the break statement.

Unlike C++, Java also offers a labeled break statement that 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 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.

Scanner in = new Scanner(System.in);

int n;

read_data:

white (. . .) // this loop statement is tagged with the label

{

. . .

for (. . .) // this inner loop is not labeled

{

System.out.print(“Enter a number >= 0: “);

n = in.nextInt();

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:

Scanner in = new Scanner(System.in); white (sum < goat)

{

System.out.print(“Enter a number: “);

n = in.nextInt();

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++)

{

System.out.print(“Enter a number, -1 to quit: “);

n = in.nextInt();

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.

Source: Horstmann Cay S. (2019), Core Java. Volume I – Fundamentals, Pearson; 11th edition.

Leave a Reply

Your email address will not be published. Required fields are marked *