You are on page 1of 15

Chapter Three: Decision and Repetition Statements

The Java keywords for controlling program flow are nearly identical to C++. This is one
of the most obvious ways in which Java shows its legacy as a derivative of this language.
In this section, you will see how to use Java's control flow statements.
3.1. Selection
The Java language provides two alternative statements -if statements and switch
statements - for selecting among the given alternatives.
3.1.1. The if Statement
The Java if statement is a test of any Boolean expression. If the Boolean expression
evaluates to true, the statement following the if statement is executed. On the other hand,
if the Boolean expression evaluates to false, the statement following the if is not
executed. For example, consider the following code fragment:
import java.util.Date;
Date today = new Date();
if (today.getDay == 0) then
System.out.println("It is Sunday.");
This code uses the java.util.Date package and creates a variable named today that will
hold the current date. The getDay member method is then applied to today and the result
compared to 0. A return value of 0 for getDay indicates that the day is Sunday, so if the
Boolean expression today.getDay = = 0 is true, a message is displayed. If today isn't
Sunday, no action occurs. In Java, the expression used within an if statement must
evaluate to a Boolean.
The Java developers included an else statement that can be executed whenever an if
statement evaluates to false. This can be seen in the following sample code:
import java.util.Date;
Date today = new Date();
if (today.getDay == 0) then
System.out.println("It is Sunday.");
else
System.out.println("It is NOT Sunday.");

1
In this case, the same message will be displayed whenever it is Sunday, but a different
message will be displayed whenever it is not Sunday. Both examples so far have only
shown the execution of a single statement within the if or the else cases. By enclosing the
statements within curly braces, you can execute as many lines of code as you'd like. This
can be seen in the following example that makes some suggestions about how to spend
each day of the week:
import java.util.Date;
Date today = new Date();
if (today.getDay == 0) then {
System.out.println("It is Sunday.");
System.out.println("And a good day for golf.");
}
else {
System.out.println("It is NOT Sunday.");
System.out.println("But still a good day for golf.");
}
Because it's possible to execute whatever code you desire in the else portion of an
if…else block, you may have already reasoned that it is possible to execute another if
statement inside the else statement of the first if statement. This is commonly known as
an if…else if…else block, an example of which follows:
import java.util.Date;
Date today = new Date();
if (today.getDay == 0) then
System.out.println("It is Sunday.");
else if (today.getDay == 1) then
System.out.println("It is Monday.");
else if (today.getDay == 2) then
System.out.println("It is Tuesday.");
else if (today.getDay == 3) then
System.out.println("It is Wednesday.");
else if (today.getDay == 4) then

2
System.out.println("It is Thursday.");
else if (today.getDay == 5) then
System.out.println("It is Friday.");
else
System.out.println("It must be Saturday.");
3.1.2. The switch Statement
As you can see from the previous code sample, a lengthy series of if…else if…else
statements can get complicated and hard to read as the number of cases increases.
Fortunately, you can avoid this problem by using Java's switch statement. The Java
switch statement is ideal for testing a single expression against a series of possible values
and executing the code associated with the matching case statement, as shown in the
following example:
import java.util.Date;
Date today = new Date();
switch (today.getDay) {
case 0: // Sunday
System.out.println("It is Sunday.");
break;
case 1: // Monday
System.out.println("It is Monday.");
break;
case 2: // Tuesday
System.out.println("It is Tuesday.");
break;
case 3: // Wednesday
System.out.println("It is Wednesday.");
break;
case 4: // Thursday
System.out.println("It is Thursday.");
break;
case 5: // Friday

3
System.out.println("It is Friday.");
System.out.println("Have a nice weekend!");
break;
default: // Saturday
System.out.println("It must be Saturday.");
}
System.out.println("All done!");
You should have noticed that each day has its own case within the switch. The Saturday
case (where today.getDay = 6) is not explicitly given but is instead handled by the default
case. Any switch block may include an optional default case that will handle any values
not caught by an explicit case.
Within each case, there can be multiple lines of code. The block of code that will execute
for the Friday case, for example, contains three lines. The first two lines will simply
display informational messages, but the third is a break statement. The keyword break is
used within a case statement to indicate that the flow of the program should move to the
first line following the switch block. In this example, break appears as the last statement
in each case except the default and will cause program execution to move to the line that
prints "All done!" The break statement was left out of the default block because by that
point in the code, the switch block was ending, and there was no point in using an explicit
command to exit the switch.
If, as the previous example seems to imply, you always need to include a break statement
at the end of each block, why not just leave break out and have Java assume that after a
block executes, control should move outside the switch block? The answer is that there
are times when you do not want to break out of the switch statement after executing the
code for a specific case value. For example, consider the following code that could be
used as a scheduling system for physicians:
import java.util.Date;
Date today = new Date();
switch (today.getDay) {
case 0: // Sunday
case 3: // Wednesday

4
case 6: // Saturday
System.out.println("It's Golf Day!");
break;
case 2: // Tuesday
System.out.println("Tennis at 8:00 am");
case 1: // Monday
case 4: // Thursday
case 5: // Friday
System.out.println("Office Hours: 10:00 - 5:00");
break;
}
System.out.println("All done!");
This example illustrates a couple of key concepts about switch statements. First, you'll
notice that it is possible to have multiple cases execute the same block of code, as
follows:
case 0: // Sunday
case 3: // Wednesday
case 6: // Saturday
System.out.println("It's Golf Day!");
break;
This code will result in the message "It's Golf Day" being displayed if the current day is
Wednesday, Saturday, or Sunday. If you collect the three cases together without any
intervening break statements, each will execute the same code. But consider what
happens on Tuesday when the following code executes:
case 2: // Tuesday
System.out.println("Tennis at 8:00 am");
Certainly a reminder about the message match will be displayed, but this case doesn't end
with a break statement. Because Tuesday's code doesn't end with a break statement, the
program will continue executing the code in the following cases until a break is
encountered. This means that Tuesday's code flows into the code used for Monday,
Thursday, and Friday as shown in the following:

5
case 2: // Tuesday
System.out.println("Tennis at 8:00 am");
case 1: // Monday
case 4: // Thursday
case 5: // Friday
System.out.println("Office Hours: 10:00 - 5:00");
break;
This will result in the following messages being displayed every Tuesday:
Tennis at 8:00 am
Office Hours: 10:00 - 5:00
On Monday, Thursday, and Friday, only the latter message will display.
In addition to writing switch statements that use integer cases, you can use character
values as shown in the following example:
switch (aChar) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
System.out.println("It's a vowel!");
break;
default:
System.out.println("It's a consonant!");
}
3.2. Iteration
Iteration is an important concept in any computer language. Without the ability to loop or
iterate through a set of values, our ability to solve real-world problems would be severely
limited. Java's iteration statements are nearly identical to those found in C and C++ and
include for loops, while loops, and do…while loops.

6
3.2.1. The for Statement
The first line of a for loop enables you to specify a starting value for a loop counter,
specify the test condition that will exit the loop, and indicate how the loop counter should
be incremented (decremented) after each pass through the loop. The syntax of a Java for
statement is as follows:
for (initialization; testExpression; incremement)
statement
For example, a sample for loop may appear as follows:
int count;
for (count=0; count<100; count++)
System.out.println("count = " + count);
In this example, the initialization statement of the for loop sets count to 0. The test
expression, count < 100, indicates that the loop should continue as long as count is less
than 100. Finally, the increment statement increases the value of count by one. As long as
the test expression is true, the statement following the for loop setup will be executed, as
follows:
System.out.println("count = " + count);
Of course, you probably need to do more than one thing inside the loop. This is as easy to
do as using curly braces to indicate the scope of the for loop, as shown in the following:
int count;
for (count=0; count<100; count++) {
YourMethod(count);
System.out.println("Count = " + count);
}
One nice shortcut that can be taken with a Java for loop is to declare and initialize the
variable used in the loop. For example, in the following code, the variable count is
declared directly within the for loop:
for (int count=0; count<100; count++)
System.out.println("Count = " + count);
It may look like an unimportant difference whether you declare a variable before a for
loop or within the loop. However, there are advantages to declaring the variable within

7
the loop. First, it makes your intention to use the variable within the loop clear. If the
variable is declared above the for loop, how will you remember (and how will future
programmers know) that the variable was intended to be used only within the loop?
Second, a variable declared within the for loop will go out of scope at the end of the loop.
This means you could not write the following code:
for (int count=0; count<100; count++)
System.out.println("Count = " + count);
System.out.println("Loop exited with count = " + count);
The last line cannot find a variable named count because count goes out of scope when
the for loop terminates. This means that, in addition to making the intended purpose of
the variable clearer, it is also impossible to accidentally bypass that intent and use the
variable outside the loop.
You can also leave out portions of the first line of a for loop. In the following example,
the increment statement has been left out:
for (int count=0; count<100; ) {
count += 2;
System.out.println("Count = " + count);
}
Of course, leaving the increment statement out of the for loop declaration in this example
doesn't achieve any useful purpose since count is incremented inside the loop.
It is possible to get even fancier with a Java for loop by including multiple statements or
conditions. For example, consider the following code:
for (int up=0, down = 20; up < down; up++, down -= 2 ) {
System.out.println("Up = " + up + "\tDown = " + down);
}
This loop starts the variable up at 0 and increments it by 1. It also starts the variable down
at 20 and decrements it by 2 for each pass through the loop. The loop continues until up
has been incremented enough that it is equal to or greater than the variable down.
The test expression portion of a Java for loop can be any Boolean expression. Because of
this, it does not need to be a simple test (x < 10), as shown in the preceding examples.
The test expression can be a method call, a method call combined with a value test, or

8
anything that can be phrased as a Boolean expression. For example, suppose you want to
write a method that will display a message indicating the first year since World War II
that the Chicago Cubs appeared in the World Series. You could do this as follows:
public boolean DidCubsPlayInWorldSeries(int year) {
boolean retval;
switch(year) {
case 1907: // these are years the Cubs won
case 1908:
retval = true;
break;
case 1906: // these are years the Cubs lost
case 1910:
case 1918:
case 1929:
case 1932:
case 1935:
case 1938:
case 1945:
retval = true;
break;
default:
retval = false;
}
return retval;
}
public void FindFirstAfterWWII() {
for (int year=1946; DidCubsPlayInWorldSeries(year)==false; year++) {
System.out.println("The Cubs didn't play in " + year);
}
}

9
The method DidCubsPlayInWorldSeries is passed an integer value indicating the year
and returns a Boolean value that indicates whether or not the Cubs made it to the World
Series in that year. This method is an example of the switch statement shown earlier in
this chapter.
The method FindFirstAfterWWII uses a for loop to find a year in which the Cubs played
in the World Series. The loop starts year with 1946 and increments year by one for each
pass through the loop. The test expression for the loop will allow the loop to continue as
long as the method DidCubsPlayInWorldSeries returns false. This is a useful example
because it shows that a method can be called within the test expression of a for loop.
Unfortunately, it is a bad example in that the Cubs haven't won the World Series since the
goose step was popular in Berlin, and there is no sign of that changing in the near future.
In other words, a loop that looks for a Cubs World Series appearance after 1945 is an
infinite loop.
3.2.2. The while Statement
Related to the for loop is the while loop. The syntax for a while loop is as follows:
while (booleanExpression)
statement
As you can tell from the simplicity of this, the Java while loop does not have the built-in
support for initializing and incrementing variables that its for loop does. Because of this,
you need to be careful to initialize loop counters prior to the loop and increment them
within the body of the while loop. For example, the following code fragment will display
a message five times:
int count = 0;
while (count < 5) {
System.out.println("Count = " + count);
count++;
}

10
3.2.3. The do…while Statement

The final looping construct in Java is the do…while loop. The syntax for a do…while
loop is as follows:
do {
statement
} while (booleanExpression);
This is similar to a while loop except that a do…while loop is guaranteed to execute at
least once. It is possible that a while loop may not execute at all depending on the test
expression used in the loop. For example, consider the following method:
public void ShowYears(int year) {
while (year < 2000) {
System.out.println("Year is " + year);
year++;
}
}
This method is passed a year value, then loops over the year displaying a message as long
as the year is less than 2000. If year starts at 1996, then messages will be displayed for
the years 1996, 1997, 1998, and 1999. However, what happens if year starts at 2010?
Because the initial test, year < 2000, will be false, the while loop will never be entered.
Fortunately, a do…while loop can solve this problem. Because a do…while loop performs
its expression testing after the body of the loop has executed for each pass, it will always
be executed at least once. This is a very valid distinction between the two types of loop,
but it can also be a source of potential errors. Whenever you use a do…while loop, you
should be careful to consider the first pass through the body of the loop.
3.3. Jumping
Of course, it is not always easy to write all of your for, while and do…while loops so that
they are easy to read and yet the loops terminate on exactly the right pass through the
loop. Java makes it easier to jump out of loops and to control other areas of program flow
with its break and continue statements.

11
3.3.1. The break Statement
Earlier in this chapter, you saw how the break statement is used to exit a switch
statement. In a similar manner, break can be used to exit a loop. As an example of this,
consider the following code:
int year = 1909;
while (DidCubsWinTheWorldSeries(year) == false) {
System.out.println("Didn't win in " + year);
if (year >= 3000) {
System.out.println("Time to give up. Go White Sox!");
break;
}
}
System.out.println("Loop exited on year " + year);
This example shows a while loop that will continue to execute until it finds a year that the
Chicago Cubs won the World Series. Because they haven't won since 1908 and the loop
counter year starts with 1909, it has a lot of looping to do. For each year they didn't win,
a message is displayed. However, even die-hard Cubs fans will eventually give up and
change allegiances to the Chicago White Sox. In this example, if the year is 3000 or later,
a message is displayed and then a break is encountered. The break statement will cause
program control to move to the first statement after the end of the while loop. In this case,
that will be the following line:
System.out.println("Loop exited on year " + year);
3.3.2. The continue Statement
Just as a break statement can be used to move program control to immediately after the
end of a loop, the continue statement can be used to force program control back to the top
of a loop. Suppose you want to write a method that will count and display the number of
times the Cubs have won the World Series this century. One way to do this would be to
first see if the Cubs played in the World Series and then see if they won. This could be
done as follows:

12
int timesWon = 0;
for (int year=1900; year <= 2000; year++) {
if (DidCubsPlayInWorldSeries(year) = false)
continue;
if (DidCubsWinWorldSeries(year)) {
System.out.println("Cubbies won in " + year + "!");
timesWon++;
}
}
System.out.println("The Cubs won " + timesWon + " times.");
In this case, a for loop is used to iterate through the years from 1900 to 2000. The first
line within the loop tests to see if the Cubs played in the World Series. If they didn't, the
continue statement is executed. This moves program control back to the for loop. At that
point, year is incremented and the expression year <= 2000 is retested. If year is less than
or equal to 2000, the loop continues. If, however, DidCubsPlayInWorldSeries equals true,
then the continue statement is skipped, and the next test is performed to see if the Cubs
won that year.
3.3.3. Using Labels
Java does not include a goto statement. However, the fact that goto is a reserved word
indicates that it may be added in a future version. Instead of goto, Java allows you to
combine break and continue with a label. This has an effect similar to a goto in that it
allows a program to reposition control. In order to understand the use of labels with break
and continue, consider the following example:
public void paint(Graphics g) {
int line=1;
outsideLoop:
for(int out=0; out<3; out++) {
g.drawString("out = " + out, 5, line * 20);
line++;
for(int inner=0;inner < 5; inner++) {
double randNum = Math.random();

13
g.drawString(Double.toString(randNum), 15, line * 20);
line++;
if (randNum < .10) {
g.drawString("break to outsideLoop", 25, line * 20);
line++;
break outsideLoop;
}
if (randNum < .60) {
g.drawString("continue to outsideLoop", 25, line * 20);
line++;
continue outsideLoop;
}
}
}
g.drawString("all done", 50, line * 20);
}
This example includes two loops. The first loops on the variable out, and the second
loops on the variable inner. The outer loop has been labeled by the following line:
outsideLoop:
This statement will serve as a placeholder and as a name for the outer loop. A random
number between 0 and 1 is generated for each iteration through the inner loop. This
number is displayed on the screen. If the random number is less than 0.10, the statement
break outsideLoop is executed. A normal break statement in this position would break out
of the inner loop. However, since this is a labeled break statement, it has the effect of
breaking out of the loop identified by the name. In this case, program control passes to
the line that displays "all done" since that is the first line after outsideLoop.
On the other hand, if the random number is not less than 0.10, the number is compared to
0.60. If it is less than this, the statement continue outsideLoop is executed. A normal,
unlabeled continue statement at this point would have the effect of transferring program
control back to the top of the inner loop. Because this is a labeled continue statement,
program control is transferred to the start of the named loop.

14
The first pass through the outer loop resulted in four passes through the inner loop. When
the value 0.518478 was generated, it caused the continue outsideLoop to execute because
the number is less than 0.60. The next pass through the outer loop was similar except that
it did a continue of the outer loop after only one iteration through the inner loop. Finally,
on the third pass through the outer loop, the program generated a value lower than 0.10,
which caused the program to break to the outer loop. You can see that, at this point, the
next line of code to be executed was the first line of code after the outer loop (the line
that prints the message "all done").

15

You might also like