Control Flow Statements
Table of Contents
1. Introduction
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.
2. The if-then Statement
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.
Example
/** * A Class used to demonstrate If-Then Statement. * * @author vasanth * */ public class IfThenStatementDemo { /** * Main. * * @param args */ public static void main(String[] args) { int a = 10, b = 20; if (a > b) { System.out.println("a is Greater than b"); } } }
If this test evaluates to false (meaning that a is not greater than b), control jumps to the end of the if-then statement.
Our above condition we can write in two ways,
if (a > b) { System.out.println("a is Greater than b"); }
Or
if (a > b) System.out.println("a is Greater than b");
We can omit braces if we have only one statement to execute with in our condition else if we have more than one statement to be executed then we need to have braces.
3. The if-then-else Statement
The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to false.
Example
/** * A Class used to demonstrate If-Then-Else Statement. * * @author vasanth * */ public class IfThenElseStatementDemo { /** * Main. * * @param args */ public static void main(String[] args) { int a = 10, b = 20; if (a > b) { System.out.println("a is Greater than b"); } else { System.out.println("b is Greater than a"); } } }
Output
b is Greater than a
4. The switch Statement
Unlike if-then and if-then-else statements, the switch statement can have a number of possible execution paths. A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types, the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer.
Example
/** * A Class used to demonstrate Switch Statement. * * @author vasanth * */ public class SwitchDemo { /** * Main. * * @param args */ public static void main(String[] args) { int month = 8; String monthString; switch (month) { case 1: monthString = "January"; break; case 2: monthString = "February"; break; case 3: monthString = "March"; break; case 4: monthString = "April"; break; case 5: monthString = "May"; break; case 6: monthString = "June"; break; case 7: monthString = "July"; break; case 8: monthString = "August"; break; case 9: monthString = "September"; break; case 10: monthString = "October"; break; case 11: monthString = "November"; break; case 12: monthString = "December"; break; default: monthString = "Invalid month"; break; } System.out.println(monthString); } }
Output
August
The body of a switch statement is known as a switch block. A statement in the switch block can be labeled with one or more case or default labels. The switch statement evaluates its expression, then executes all statements that follow the matching case label.
You could also display the name of the month with if-then-else statements. Deciding whether to use if-then-else statements or a switch statement is based on readability and the expression that the statement is testing. An if-then-else statement can test expressions based on ranges of values or conditions, whereas a switch statement tests expressions based only on a single integer, enumerated value, or String object.
Another point of interest is the break statement. 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, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.
In Java SE 7 and later, you can use a String object in the switch statement's expression. The String in the switch expression is compared with the expressions associated with each case label as if the String.equals method were being used.
5. The while and do-while Statements
The while statement continually executes a block of statements while a particular condition is true. Its syntax can be expressed as:
while (expression) { statement(s) }
The while statement evaluates expression, which must return a boolean value. If the expression evaluates to true, the while statement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false.
Example
Using the while statement to print the values from 1 through 10
/** * A Class used to demonstrate While Statement. * * @author vasanth * */ public class WhileDemo { /** * Main. * * @param args */ public static void main(String[] args) { int count = 1; while (count < 11) { System.out.println("Count is: " + count); count++; } } }
Output
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
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.
Example
/** * A Class used to demonstrate Do-While Statement. * * @author vasanth * */ public class DoWhileDemo { /** * Main. * * @param args */ public static void main(String[] args) { int count = 1; do { System.out.println("Count is: " + count); count++; } while (count < 11); } }
Output
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
6. The for Statement
The for statement provides a compact way to iterate over a range of values. The general form of the for statement can be expressed as follows:
for (initialization; termination; increment) { statement(s) }
When using this version of the for statement, keep in mind that:
-
The initialization expression initializes the loop; it's executed once, as the loop begins.
-
When the termination expression evaluates to false, the loop terminates.
-
The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.
Example
/** * A Class used to demonstrate For Statement. * * @author vasanth * */ public class ForDemo { /** * Main. * * @param args */ public static void main(String[] args) { for (int i = 1; i < 11; i++) { System.out.println("Count is: " + i); } } }
Output
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
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.
Example
/** * A Class used to demonstrate Enhanced For Statement. * * @author vasanth * */ public class EnhancedForDemo { /** * Main. * * @param args */ 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); } } }
Output
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
7. Branching Statements
The break Statement
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.
Example
This program searches for the number 12 in an array. The break statement, terminates the for loop when that value is found. Control flow then transfers to the statement after the for loop.
/** * A Class used to demonstrate Break Statement. * * @author vasanth * */ public class BreakDemo { /** * Main. * * @param args */ public static void main(String[] args) { int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076, 2000, 8, 622, 127 }; int searchfor = 12; int i; boolean foundIt = false; for (i = 0; i < arrayOfInts.length; i++) { if (arrayOfInts[i] == searchfor) { foundIt = true; break; } } if (foundIt) { System.out.println("Found " + searchfor + " at index " + i); } else { System.out.println(searchfor + " not in the array"); } } }
Output
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.
Example
The following program, 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"):
/** * A Class used to demonstrate Break with label Statement. * * @author vasanth * */ public class BreakWithLabelDemo { /** * Main. * * @param args */ public static void main(String[] args) { int[][] arrayOfInts = { { 32, 87, 3, 589 }, { 12, 1076, 2000, 8 }, { 622, 127, 77, 955 } }; int searchfor = 12; 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"); } } }
Output
Found 12 at 1, 0
The continue 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.
Example
The following program , steps through a String, counting the occurrences 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.
/** * A Class used to demonstrate Continue Statement. * * @author vasanth * */ public class ContinueDemo { /** * Main. * * @param args */ public static void main(String[] args) { String searchMe = "peter piper picked a " + "peck of pickled peppers"; int max = searchMe.length(); int numPs = 0; for (int i = 0; i < max; i++) { // interested only in p's if (searchMe.charAt(i) != 'p') continue; // process p's numPs++; } System.out.println("Found " + numPs + " p's in the string."); } }
Output
Found 9 p's in the string.
A labeled continue statement skips the current iteration of an outer loop marked with the given label.
Example
The following example program, 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, uses the labeled form of continue to skip an iteration in the outer loop.
/** * A Class used to demonstrate Continue With Label Statement. * * @author vasanth * */ public class ContinueWithLabelDemo { /** * Main. * * @param args */ public static void main(String[] args) { String searchMe = "Look for a substring in me"; String substring = "sub"; boolean foundIt = false; int max = searchMe.length() - substring.length(); 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"); } }
Output
Found it
The return Statement
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 returned 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;