Java - Control Flow Statements
Java - Control Flow Statements
This section describes the control flow statements supported by the Java programming language. It covers the
decisions-making, looping, and branching statements that enable your programs to conditionally execute
particular blocks of code.
The statements inside your source files are generally executed from top to bottom, in the order that they appear.
Control flow statements, however, break up the flow of execution by employing decision making, looping, and
branching, enabling your program to conditionally execute particular blocks of code. This section describes the
decision-making statements (if-then, if-then-else, switch), the looping statements (for, while, do-
while), and the branching statements (break, continue, return) supported by the Java programming
language.
The if-then statement is the most basic of all the control flow statements. It tells your program to execute a
certain section of code only if a particular test evaluates to true. For example, the Bicycle class could allow
the brakes to decrease the bicycle's speed only if the bicycle is already in motion. One possible implementation
of the applyBrakes method could be as follows:
void applyBrakes(){
if (isMoving){ // the "if" clause: bicycle must moving
currentSpeed--; // the "then" clause: decrease current speed
}
}
If this test evaluates to false (meaning that the bicycle is not in motion), control jumps to the end of the if-
then statement.
In addition, the opening and closing braces are optional, provided that the "then" clause contains only one
statement:
void applyBrakes(){
if (isMoving) currentSpeed--; // same as above, but without braces
}
Deciding when to omit the braces is a matter of personal taste. Omitting them can make the code more brittle. If
a second statement is later added to the "then" clause, a common mistake would be forgetting to add the newly
required braces. The compiler cannot catch this sort of error; you'll just get the wrong results.
The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to false.
You could use an if-then-else statement in the applyBrakes method to take some action if the brakes are
applied when the bicycle is not in motion. In this case, the action is to simply print an error message stating that
the bicycle has already stopped.
void applyBrakes(){
if (isMoving) {
currentSpeed--;
} else {
System.err.println("The bicycle has already stopped!");
}
}
The following program, IfElseDemo, assigns a grade based on the value of a test score: an A for a score of 90%
or above, a B for a score of 80% or above, and so on.
class IfElseDemo {
public static void main(String[] args) {
The following program, SwitchDemo, declares an int named month whose value represents a month out of the
year. The program displays the name of the month, based on the value of month, using the switch statement.
class SwitchDemo {
public static void main(String[] args) {
int month = 8;
switch (month) {
case 1: System.out.println("January"); break;
case 2: System.out.println("February"); break;
case 3: System.out.println("March"); break;
case 4: System.out.println("April"); break;
case 5: System.out.println("May"); break;
case 6: System.out.println("June"); break;
case 7: System.out.println("July"); break;
case 8: System.out.println("August"); break;
case 9: System.out.println("September"); break;
case 10: System.out.println("October"); break;
case 11: System.out.println("November"); break;
case 12: System.out.println("December"); break;
default: System.out.println("Invalid month.");break;
}
}
}
Of course, you could also implement the same thing with if-then-else statements:
int month = 8;
if (month == 1) {
System.out.println("January");
} else if (month == 2) {
System.out.println("February");
}
. . . // and so on
Deciding whether to use if-then-else statements or a switch statement is sometimes a judgment call. You
can decide which one to use based on readability and other factors. An if-then-else statement can be used to
make decisions based on ranges of values or conditions, whereas a switch statement can make decisions based
only on a single integer or enumerated value.
Another point of interest is the break statement after each case. Each break statement terminates the enclosing
switch statement. Control flow continues with the first statement following the switch block. The break
statements are necessary because without them, case statements fall through; that is, without an explicit break,
control will flow sequentially through subsequent case statements. The following program, SwitchDemo2,
illustrates why it might be useful to have case statements fall through:
class SwitchDemo2 {
public static void main(String[] args) {
int month = 2;
int year = 2000;
int numDays = 0;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
numDays = 31;
break;
case 4:
case 6:
case 9:
case 11:
numDays = 30;
break;
case 2:
if ( ((year % 4 == 0) && !(year % 100 == 0))
|| (year % 400 == 0) )
numDays = 29;
else
numDays = 28;
break;
default:
System.out.println("Invalid month.");
break;
}
System.out.println("Number of Days = " + numDays);
}
}
Number of Days = 29
Technically, the final break is not required because flow would fall out of the switch statement anyway.
However, we recommend using a break so that modifying the code is easier and less error-prone. The default
section handles all values that aren't explicitly handled by one of the case sections.
You can implement an infinite loop using the while statement as follows:
while (true){
// your code goes here
}
The Java programming language also provides a do-while statement, which can be expressed as follows:
do {
statement(s)
} while (expression);
The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop
instead of the top. Therefore, the statements within the do block are always executed at least once, as shown in
the following DoWhileDemo program:
class DoWhileDemo {
public static void main(String[] args){
int count = 1;
do {
System.out.println("Count is: " + count);
count++;
} while (count <= 11);
}
}
The following program, ForDemo, uses the general form of the for statement to print the numbers 1 through 10
to standard output:
class ForDemo {
public static void main(String[] args){
for(int i=1; i<11; i++){
System.out.println("Count is: " + i);
}
}
}
The output of this program is:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
Notice how the code declares a local variable within the initialization expression. The scope of this variable
extends from its declaration to the end of the block governed by the for statement, so it can be used in the
termination and increment expressions as well. If the variable that controls a for statement is not needed
outside of the loop, it's best to declare the variable in the initialization expression. The names i, j, and k are
often used to control for loops; declaring them within the initialization expression limits their life span and
reduces errors.
The three expressions of the for loop are optional; an infinite loop can be created as follows:
The for statement also has another form designed for iteration through collections and arrays This form is
sometimes referred to as the enhanced for statement, and can be used to make your loops more compact and
easy to read. To demonstrate, consider the following array, which holds the numbers 1 through 10:
The following program, EnhancedForDemo, uses the enhanced for to loop through the array:
class EnhancedForDemo {
public static void main(String[] args){
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
for (int item : numbers) {
System.out.println("Count is: " + item);
}
}
}
In this example, the local variable item holds the current value from the numbers array. The output from this
program is the same as before:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
We recommend using this form of the for statement instead of the general form whenever possible.
Branching Statements
The break statement has two forms: labeled and unlabeled. You saw the unlabeled form in the previous
discussion of the switch statement. You can also use an unlabeled break to terminate a for, while, or do-
while loop, as shown in the following BreakDemo program:
class BreakDemo {
public static void main(String[] args) {
int i;
boolean foundIt = false;
if (foundIt) {
System.out.println("Found " + searchfor
+ " at index " + i);
} else {
System.out.println(searchfor
+ " not in the array");
}
}
}
This program searches for the number 12 in an array. The break statement, shown in boldface, terminates the
for loop when that value is found. Control flow then transfers to the print statement at the end of the program.
This program's output is:
Found 12 at index 4
An unlabeled break statement terminates the innermost switch, for, while, or do-while statement, but a
labeled break terminates an outer statement. The following program, BreakWithLabelDemo, is similar to the
previous program, but uses nested for loops to search for a value in a two-dimensional array. When the value is
found, a labeled break terminates the outer for loop (labeled "search"):
class BreakWithLabelDemo {
public static void main(String[] args) {
int i;
int j = 0;
boolean foundIt = false;
search:
for (i = 0; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length; j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search;
}
}
}
if (foundIt) {
System.out.println("Found " + searchfor +
" at " + i + ", " + j);
} else {
System.out.println(searchfor
+ " not in the array");
}
}
}
Found 12 at 1, 0
The break statement terminates the labeled statement; it does not transfer the flow of control to the label.
Control flow is transferred to the statement immediately following the labeled (terminated) statement.
The continue statement skips the current iteration of a for, while , or do-while loop. The unlabeled form
skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop. The
following program, ContinueDemo , steps through a String, counting the occurences of the letter "p". If the
current character is not a p, the continue statement skips the rest of the loop and proceeds to the next character.
If it is a "p", the program increments the letter count.
class ContinueDemo {
public static void main(String[] args) {
//process p's
numPs++;
}
System.out.println("Found " + numPs + " p's in the string.");
}
}
Here is the output of this program:
Found 9 p's in the string.
To see this effect more clearly, try removing the continue statement and recompiling. When you run the
program again, the count will be wrong, saying that it found 35 p's instead of 9.
A labeled continue statement skips the current iteration of an outer loop marked with the given label. The
following example program, ContinueWithLabelDemo, uses nested loops to search for a substring within
another string. Two nested loops are required: one to iterate over the substring and one to iterate over the string
being searched. The following program, ContinueWithLabelDemo, uses the labeled form of continue to skip an
iteration in the outer loop.
class ContinueWithLabelDemo {
public static void main(String[] args) {
test:
for (int i = 0; i <= max; i++) {
int n = substring.length();
int j = i;
int k = 0;
while (n-- != 0) {
if (searchMe.charAt(j++)
!= substring.charAt(k++)) {
continue test;
}
}
foundIt = true;
break test;
}
System.out.println(foundIt ? "Found it" :
"Didn't find it");
}
}
Found it
The last of the branching statements is the return statement. The return statement exits from the current
method, and control flow returns to where the method was invoked. The return statement has two forms: one
that returns a value, and one that doesn't. To return a value, simply put the value (or an expression that
calculates the value) after the return keyword.
return ++count;
The data type of the returmed value must match the type of the method's declared return value. When a method
is declared void, use the form of return that doesn't return a value.
return;
Questions
1. The most basic control flow statement supported by the Java programming language is the ___
statement.
2. The ___ statement allows for any number of possible execution paths.
3. The ___ statement is similar to the while statement, but evaluates its expression at the ___ of the loop.
4. How do you write an infinite loop using the for statement?
5. How do you write an infinite loop using the while statement?
Exercises
if (aNumber >= 0)
if (aNumber == 0) System.out.println("first string");
else System.out.println("second string");
System.out.println("third string");
a. What output do you think the code will produce if aNumber is 3?
b. Write a test program containing the code snippet; make aNumber 3. What is the output of the
program? Is it what you predicted? Explain why the output is what it is; in other words, what is
the control flow for the code snippet?
c. Using only spaces and line breaks, reformat the code snippet to make the control flow easier to
understand.
d. Use braces, { and }, to further clarify the code.