Home > Articles > Programming > Java

This chapter is from the book

Control Flow

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.

The Java control flow constructs are identical to those in C and C++, with two 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).

The Java control flow constructs are identical to those in C and C++, with two 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).

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

However, it is not possible to 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
      . . .
   }
}

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.

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:

{
   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.)

03fig07.gifFigure 3-7. Flowchart for the if statement

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.

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 (see Figure 3-8):

if (condition) statement1 else statement2
   

03fig08.gifFigure 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.

Repeated if . . . else if . . . alternatives are very 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");
}

03fig09.gifFigure 3-9. Flowchart for the if/else if (multiple branches)

Indeterminate Loops

In Java, as in all programming languages, there are control structures that let you repeat statements. There are two forms for repeating loops that are best when you do not know how many times a loop should be processed (these are “indeterminate loops”).

First, there is the while loop that only executes the body of the loop 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).

03fig10.gifFigure 3-10. Flowchart for the while statement

In Example 3-3, we write a program to determine 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 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++;
   }
   

(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. This is done with the do/while loop. Its syntax looks like this:

do statement while (condition);
   

This statement executes the block and only then tests the condition. It then repeats the block and retests the condition, and so on. For instance, the code in Example 3-4 computes the new balance in your retirement account and then asks you 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.

Example 3-3 Retirement.java

 1. import javax.swing.*;
 2.
 3. public class Retirement
 4. {
 5.    public static void main(String[] args)
 6.    {
 7.       // read inputs
 8.       String input = JOptionPane.showInputDialog
 9.          ("How much money do you need to retire?");
10.        double goal = Double.parseDouble(input);
11.
12.       input = JOptionPane.showInputDialog
13.          ("How much money will you contribute every year?");
14.       double payment =  Double.parseDouble(input);
15.
16.       input = JOptionPane.showInputDialog
17.          ("Interest rate in %:");
18.       double interestRate =  Double.parseDouble(input);
19.
20.       double balance = 0;
21.       int years = 0;
22.
23.       // update account balance while goal isn't reached
24.       while (balance < goal)
25.       {  // add this year's payment and interest
26.
27.          balance += payment;
28.          double interest = balance * interestRate / 100;
29.          balance += interest;
30.
31.          years++;
32.       }
33.
34.       System.out.println
35.          ("You can retire in " + years + " years.");
36.       System.exit(0);
37.    }
38. }

03fig11.gifFigure 3-11. Flowchart for the do/while statement

Example 3-4 Retirement2.java

 1. import java.text.*;
 2. import javax.swing.*;
 3.
 4. public class Retirement2
 5. {
 6.    public static void main(String[] args)
 7.    {
 8.       String input = JOptionPane.showInputDialog
 9.          ("How much money will you contribute every year?");
10.       double payment =  Double.parseDouble(input);
11.
12.       input = JOptionPane.showInputDialog
13.          ("Interest rate in %:");
14.       double interestRate =  Double.parseDouble(input);
15.
16.       double balance = 0;
17.       int year = 0;
18.
19.       NumberFormat formatter
20.          = NumberFormat.getCurrencyInstance();
21.
22.       // update account balance while user isn't ready to retire
23.       do
24.       {
25.          // add this year's payment and interest
26.          balance += payment;
27.          double interest = balance * interestRate / 100;
28.          balance += interest;
29.
30.          year++;
31.
32.          // print current balance
33.          System.out.println("After year " + year
34.             + ", your balance is "
35.             + formatter.format(balance));
36.
37.          // ask if ready to retire and get input
38.          input = JOptionPane.showInputDialog
39.             ("Ready to retire? (Y/N)");
40.          input = input.toUpperCase();
41.       }
42.       while (input.equals("N"));
43.
44.       System.exit(0);
45.    }
46. }

Determinate Loops

The for loop is a very general construct to support iteration that is 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);

03fig12.gifFigure 3-12. Flowchart for the for statement

The first slot of the for statement usually holds the counter initialization. The second slot gives the condition which 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:

for (int i = 10; i > 0; i--)
   System.out.println("Counting down . . . " + i);
System.out.println("Blastoff!");

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

for (double x = 0; x != 10; x += 0.1) . . .

may never end. Due to 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.

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

for (double x = 0; x != 10; x += 0.1) . . .

may never end. Due to 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.

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 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 header for the loop!

int i;
for (i = 1; i <= 10; i++)
{
   . . .
}
// i 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 redefine i
{
   . . .
}

Of course, a for loop is equivalent to a while loop. More precisely,

for (statement1; expression1; expression2) statement2;
   

is completely equivalent to:

{
   statement1;
   while (expression1)
   {
   statement2;
   expression2;
   }
   }
   

Example 3-5 shows a typical example of a for loop.

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

03equ01.gif


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;
   

Example 3-5 LotteryOdds.java

 1. import javax.swing.*;
 2.
 3. public class LotteryOdds
 4. {
 5.    public static void main(String[] args)
 6.    {
 7.       String input = JOptionPane.showInputDialog
 8.          ("How many numbers do you need to draw?");
 9.       int k = Integer.parseInt(input);
10.
11.       input = JOptionPane.showInputDialog
12.          ("What is the highest number you can draw?");
13.       int n = Integer.parseInt(input);
14.
15.       /*
16.          compute binomial coefficient
17.          n * (n - 1) * (n - 2) * . . . * (n - k + 1)
18.          -------------------------------------------
19.          1 * 2 * 3 * . . . * k
20.       */
21.
22.       int lotteryOdds = 1;
23.       for (int i = 1; i <= k; i++)
24.          lotteryOdds = lotteryOdds * (n - i + 1) / i;
25.
26.       System.out.println
27.          ("Your odds are 1 in " + lotteryOdds + ". Good luck!");
28.
29.       System.exit(0);
30.    }
31. }

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 menuing system with four alternatives like that in Figure 3-13, you could use code that looks like this:

String input = JOptionPane.showInputDialog
   ("Select an option (1, 2, 3, 4)");
int choice = Integer.parseInt(input);
switch (choice)
{
   case 1:
      . . .
      break;
   case 2:
      . . .
      break;
   case 3:
      . . .
      break;
   case 4:
      . . .
      break;
   default:
       // bad input
      . . .
      break;
}

03fig13.gifFigure 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 matches, then the default clause is executed, if it is present.

Note that the case labels must be integers. You cannot test strings. For example, the following is an error:

String input = . . .;
switch (input) // ERROR
{
   case "A": // ERROR
      . . .
      break;
   . . .
}

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 behavior is plainly dangerous and a common cause for errors. For that reason, we never use the switch statement in our programs.

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 behavior is plainly dangerous and a common cause for errors. For that reason, we never use the switch statement in our programs.

Breaking 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's”). 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 to support this programming style, the labeled break.

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,

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

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 this 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
   {
   String input
   = JOptionPane.showInputDialog("Enter a number >= 0");
   n = Integer.parseInt(input);
   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 break
   if (n < 0) // check for bad situation
   {
   // deal with bad situation
   }
   else
   {
   // carry out normal processing
   }
   

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 if the loop exited normally or as a result of a break.

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

label:
            {
            . . .
            if (condition) break label; // exits block
            . . .
            }
            // jumps here when the break statement executes
            

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.

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

label:
      {
      . . .
      if (condition) break label; // exits block
      . . .
      }
      // jumps here when the break statement executes
      

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:

while (sum < goal)
{
   String input = JOptionPane.showInputDialog("Enter a number");
   n = Integer.parseInt(input);
   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, consider this loop.

for (count = 0; count < 100; count++)
{
   String input = JOptionPane.showInputDialog("Enter a number");
   n = Integer.parseInt(input);
   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.

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

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

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020