Section 2.3
Loops and Branches


THE ABILITY OF A COMPUTER TO PERFORM complex tasks is built on just a few ways of combining simple commands into control structures. In Java, there are just six such structures -- and, in fact, just three of them would be enough to write programs to perform any task. The six control structures are: the block, the while loop, the do loop, the for loop, the if statement, and the switch statement. Each of these structures is considered to be a "statement," but they are in fact structured statements that can contain one or more other statements inside themselves.


The block is the simplest type of statement. Its purpose is simply to group a sequence of statements into a single statement. The format of a block is:

             {
                 statements
             }

That is, it consists of a sequence of statements enclosed between { and }. (In fact, it is possible for a block to consists of zero statements; such a block is called an empty block, and can actually be useful at times.) Block statements usually occur inside other statements, where their purpose is to group together several statements into a unit. However, a block can be legally used wherever a statement can occur. There is one place where a block is required: As you might have already noticed, the definition of a subroutine is a block.

I should probably note at this point that Java is what is called a free-format language. There are no syntax rules about how the language has to be arranged on a page. So, for example, you could write an entire block on one line if you want. But as a matter of good programming style, you should lay out your program on the page in a way that will make its structure as clear as possible. In general, this means putting one statement per line and using indentation to indicate statements that are contained inside control structures. This is the format that I will generally use in my examples.

Here are two examples of blocks:

             {
                System.out.print("The answer is ");
                System.out.println(ans);
             }


             {  // This block exchanges the values of x and y
                int temp = x;  // declare temp and store x in it
                x = y;         // copy value of y into x
                y = temp;      // copy value of temp into y
             }

In the second example, a variable, temp, is declared inside the block. This illustrates an important property of blocks: A variable declared inside a block is completely inaccessible and invisible from outside that block. The variable is said to be local to the block. There is a general concept called the "scope" of an identifier. The scope of an identifier is the part of the program in which that identifier is valid. We can say that the scope of a variable is limited to the block in which it is declared. The point of using local variables is simply to avoid clutter and to help make the program more readable. This is an important goal, and local variables should be used where appropriate.


The block statement by itself really doesn't affect the flow of control in a program. The five remaining control structures do. They can be divided into two classes: loop statements and branching statements. You really just need one control structure from each category in order to have a completely general-purpose programming language. More than that is just convenience. In this section, I'll only discuss the while loop and the if statement. I'll get back to the others in Section 7.

A while loop is used to repeat a given statement over and over. Of course, its not likely that you would want to repeat forever. That would be an infinite loop, which is generally a bad thing. (There is an old story about computer pioneer Grace Murray Hopper, who read instructions on a bottle of shampoo telling her to " lather, rinse, repeat." As the story goes, she claims that she tried to follow the directions but that she ran out of shampoo. (In case you don't get it, this is a joke about the way that computers mindlessly follow instructions.))

To be more specific, a while loop will repeat a statement over and over, but only so long as a specified condition remains true. A while loop has the form:

             while (boolean-expression)
                  statement

Since the statement can be, and usually is, a block, many while loops have the form:

             while (boolean-expression) {
                 statements
             }

The semantics of this statement go like this: When the computer comes to a while statement, it evaluates the boolean-expression, which yields either true or false as the value. If the value is false, the computer skips over the rest of the while loop and proceeds to the next command in the program. If the value of the expression is true, the computer executes the statements inside the loop. Then it returns to the beginning of the while loop and repeats the process. That is, it re-evaluates the boolean-expression, ends the loop if the value is false and continues it if the value is true. This will continue over and over until the value of the expression is false; if that never happens, then there will be an infinite loop.

Here is an example of a while loop that simply prints out the numbers 1, 2, 3, 4, 5:

             int number = 1;
             while ( number < 5 ) {
                 System.out.println(number);
                 number = number + 1;
             }
             System.out.println("Done!");

The variable number is initialized with the value 1. So the first time through the while loop, when the computer evaluates the expression "number < 5", it is asking whether 1 is less than 5, which is true. The computer therefor proceeds to execute the two statements inside the loop. The first statement prints out "1". The second statement adds 1 to number and stores the result back into the variable number; the value of number has been changed to 2. The computer has reached the end of the loop, so it returns to the beginning and asks again whether number is less than 5. Once again this is true, so the computer executes the loop again, this time printing out 2 as the value of number and then changing the value of number to 3. It continues in this way until eventually number becomes equal to 5. At that point, the expression "number < 5" evaluates to false. So, the computer jumps past the end of the loop to the next statement and prints out the message "Done!"

By the way, you should remember that you'll never see a while loop standing by itself in a real program. It will always be inside a subroutine which is itself defined inside some class. As an example of a while loop used inside a complete program, here is a little program that computes the interest on an investment over several years:

            public class Interest2 {
            
            /*
               This class implements a simple program that
               will compute the amount of interest that is
               earned on $17,000 invested at an interest
               rate of 0.07 for 5 years.  The value of
               the investment at the end of each year
               is printed to standard output.
            */
         
            public static void main(String[] args) {
            
                double principal = 17000;  // the initial value of the investment
                double rate = 0.07;        // the annual interest rate
                
                int years = 0;  // counts the number of years that have passed
                
                while (years < 5) {
                   double interest = principal * rate;   // compute this year's interest
                   principal = principal + interest;     // add it to principal
                   years = years + 1;    // count the current year.
                   System.out.print("The value of the investment after ");
                   System.out.print(years);
                   System.out.print(" years is $");
                   System.out.println(principal);
                } // end of while loop
                               
            } // end of main()
               
         } // end of class Interest2

If you want to see the answer, you can run the equivalent applet below:

Sorry, your browser doesn't
support Java.

You should study this program, and make sure that you understand what the computer does step-by-step as is executes the while loop.


An if statement tells the computer to take one of two alternative courses of action, depending on whether the value of a given boolean-valued expression is true or false. It is an example of a "branching" or "decision" statement. An if statement has the form:

               if ( boolean-expression )
                   statement
               else
                   statement

When the computer executes an if statement, it evaluates the boolean expression. If the value is true, the computer executes the first statement and skips the statement that follows the "else". If the value of the expression is false, then the computer skips the first statement and executes the second one. Note that in any case, one and only one of the two statements inside the if statement is executed. The two statements represent alternative courses of action; the computer decides between these courses of action based on the value of the boolean expression.

In many cases, you want the computer to choose between doing something and not doing it. You can do this with an if statement that omits the else part:

               if ( boolean-expression )
                   statement

To execute this statement, the computer evaluates the expression. If the value is true, the computer executes the statement that is contained inside the if statement; if the value is false, the computer skips that statement.

As usual, each of the statement's in an if statement can be a block, so that an if statement often looks like:

               if ( boolean-expression ) {
                   statements
               }
               else {
                   statements
               }

or:

               if ( boolean-expression ) {
                   statements
               }

As an example, here is an if statement that exchanges the value of two variables, x and y, but only if x is greater than y to begin with. After this if statement has been executed, we can be sure that the value of x is definitely less than or equal to the value of y:

             if ( x > y ) {
                 int temp = x;  // declare temp and store x in it
                 x = y;         // copy value of y into x
                 y = temp;      // copy value of temp into y
             }

Finally, here is an example of an if statement that includes an else part. See if you can figure out what it does, and why it would be used:

               if ( years > 1 ) {  // handle case for 2 or more years
                   System.out.print("The value of the investment after ");
                   System.out.print(years);
                   System.out.print(" years is $");
               }
               else {  // handle case for 1 year
                   System.out.print("The value of the investment after 1 year is $");
               }  // end of if statement
               System.out.println(principal);  // this is done in any case

I'll have more to say about if statements later in this chapter. But you already know the essentials. If you never learned anything more about control structures, you would already know enough to perform any possible computing task.


[ Next Section | Previous Section | Chapter Index | Main Index ]