Control Flow Core Java

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

C++ NOTE: The Java control flow constructs are identical to those in C and C++, with a few exceptions. There is no goto, but there is a “labeled” version of break that you can use to break out of a nested loop (where you perhaps would have used a goto in C). Finally! Java SE 5.0 added a variant of the for loop that has no analog in C or C++. It is similar to the foreach loop in C#.

Block Scope

Before we get into the actual control structures, you need to know more about blocks. A block or compound statement is any number of simple Java statements that are surrounded by a pair of braces. Blocks define the scope of your variables. Blocks can be nested inside another block. Here is a block that is nested inside the block of the mainmethod.

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

C++ NOTE: In C++, it is possible to redefine a variable inside a nested block. The inner definition then shadows the outer one. This can be a source of programming errors; hence, Java does not allow it.

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, you use a block statement that takes the form

In this code all the statements surrounded by the braces will be executed when yourSales is greater than or equal to target.

Flowchart for the if statement

Flowchart for the if statement

NOTE: A block (sometimes called a compound statement) allows you to have more than one (simple) statement in any Java programming structure that might otherwise have a single (simple) statement.

The more general conditional in Java looks like this:

Flowchart for the if/else statement

Flowchart for the if/else statement

The else part is always optional. An else groups with the closest if. Thus, in the statement

the else belongs to the second if. Of course, it is a good idea to use braces to clarify this code:

Flowchart for the if/else if (multiple branches)

Flowchart for the if/else if (multiple branches)

Loops

The while loop executes a statement (which may be a block statement) while a condition is true. The general form is

The while loop will never execute if the condition is false at the outset.

Flowchart for the while statement

Flowchart for the while statement

The program in Listing below determines how long it will take to save a specific amount of money for your well-earned retirement, assuming that you deposit the same amount of money per year and that the money earns a specified interest rate.

Retirement.java

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.

(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 may never be executed. If you want to make sure a block is executed at least once, you will need to move the test to the bottom. You do that with the do/while loop. Its syntax looks like this:

This loop executes the statement (which is typically a block) and only then tests the condition. It then repeats the statement and retests the condition, and so on.

The code in Listing below computes the new balance in your retirement account and then asks if you are ready to retire:

Retirement2.java

As long as the user answers "N", the loop is repeated. 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.

Flowchart for the do/while statement

Flowchart for the do/while statement

Determinate Loops

The for loop is a general construct to support iteration that is controlled by a counter or similar variable that is updated after every iteration. As below shows, the following loop prints the numbers from 1 to 10 on the screen.

Flwchart for the for statement

Flwchart for the for statement

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 explains how to update the counter.

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 of a for statement 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:

CAUTION: Be careful about testing for equality of floating-point numbers in loops. A for loop that looks like

may never end. Because of roundoff errors, the final value may not be reached exactly. For example, in the loop above, x jumps from 9.99999999999998 to 10.09999999999998 because there is no exact binary representation for 0.1.

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.

In particular, if you define a variable inside a for statement, you cannot use the value of that variable 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!

On the other hand, you can define variables with the same name in separate for loops:

A for loop is merely a convenient shortcut for a while loop. For example,

Listing below shows a typical example of a for loop.

LotteryOdds.java

The program computes the odds on winning a lottery. For example, if you must pick 6 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

Equation

possible outcomes. The following for loop computes this value:

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 switchstatement in C and C++, warts and all.

For example, if you set up a menuing system with four alternatives like that in Figure below, you could use code that looks like this:

Flowchart for the switch statement

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.

CAUTION: It is possible for multiple alternatives to be triggered. If you forget to add a break at the end of an alternative, then execution falls through to the next alternative! This behavioris plainly dangerous and a common cause for errors. For that reason, we never use theswitch statement in our programs.

The case labels must be integers or enumerated constants. You cannot test strings. For example, the following is an error:

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:

Statements That Break Control Flow

Although the designers of Java kept the 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 loopis 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:

Now the loop is exited if either years > 100 occurs at the top of the loop or balance >= goaloccurs in the middle of the loop. Of course, you could have computed the same valuefor years without a break, like this:


But note that the test balance < goal 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.

If there was 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.

NOTE: Curiously, you can apply a label to any statement, even an if statement or a block statement, like this:

Thus, if you are lusting after a goto and if you can place a block that ends just before the place to which you want to jump, you can use a break statement! Naturally, we don’t recommend this approach. Note, however, that you can only jump out of a block, never into a block.

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:

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, consider this loop:

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.

TIP: Many programmers find the break and continue statements confusing. These statements are entirely optional—you can always express the same logic without them. Here, we never use break or continue.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Core Java Topics