You are on page 1of 13

Control Statement

Introduction Control flow statements Selection statements Iteration statements Jump statements

Objective
At the end of the chapter, you will be able to: Know about Control flow statements Use Selection statements Use Iteration statements Use Jump statements

Introduction
The computer programs are written with statements which helps in organizing the program structure and its meaning. When you write a program, you type statements into a file. In programs, the individual statement, instructions or function calls of an imperative or functional program are executed. With the increasing demand of conditions and complications arising in a particular work or in solving a program, it is necessary to control the flow of the program. Without control flow statements, the interpreter executes the statements in the order they appear in the file from left to right, top to bottom. What if you wanted to change the flow? For example, you want the program to take some decisions and do different things depending on different situations such as printing 'Good Morning' or 'Good Evening' depending on the time of the day? As you might have guessed, this is achieved using control flow statements.

Control flow Statements


A program is a group of statements that are executed to achieve a predetermined task. Statements in a program are generally executed in a sequential manner, which is called sequential execution or sequential control flow. However, by putting the decision-making statement in the program, the normal flow of the program can be controlled. Statements that control the flow of the program are called control statements. Control statements are used in programming languages to cause the flow of control to advance and branch based on changes to the state of a program.In Java, control statements can be divided under the following three categories: 1. Selection statements 2. Iteration statements

3. Jump statements
Table 1 shows categories of control flow statements available in Java and keywords list for each categories. Control flow statement category Selection statements Iteration statements Jump statements Keyword list if, else, switch, case while, do, for return, break, continue

Table 1: Control flow statements and related keywords list

Selection statements in Java


A program is a group of statements that are executed to achieve a predetermined task. Statements in a program are generally executed in a sequential manner, which is called sequential execution or sequential control flow. Selection statements are used in a program to choose different paths of execution based upon the outcome of an expression or the state of a variable. Java supports two selection statements: if and switch.

The if statement

The if statement executes a block of code only if the specified expression is true. The condition to the if statement must be an expression that evaluates to a boolean value. . If the condition evaluates to true, the statement following the if statement is executed. If the value is false, then the if block is skipped and execution continues with the rest of the program. You can either have a single statement or a block of code within an if statement. The simple if statement has the following syntax: if (condition) { statement1; } The following example demonstrates conditional execution based on if statement condition. public class IfStatementDemo { public static void main(String[] args) { int a = 10, b = 20; if (a > b) System.out.println("a > b"); if (a < b) System.out.println("b > a"); } } Output b>a

The If-else Statement


The "if-else" statement is an extension of if statement that provides another option when 'if' statement evaluates to "false" i.e. else block is executed if "if" statement is false. You can either have a single statement or a block of code within if-else blocks. The else statement is optional,but if it is present,it must be placed immediately after the code block attached to the if statement. The code block attached to the else statement is executed when the condition to the if statement evaluates to false. The general form of the if statement is given below: if (condition) { statement1; } else { statement2; } The following example demonstrates conditional execution based on if-else statement condition.

public class IfElseStatementDemo { public static void main(String[] args) { int a = 10, b = 20; if (a > b) { System.out.println("a > b"); } else { System.out.println("b > a"); } } } Output b > a

The chained If-else Statement


Under the chained format the execution evaluates all conditional expressions beginning from Expression1 (given below) until the first expression is found that evaluates to true. Then the corresponding statement sequence is executed, or, if none of the expressions evaluated to true, the statement sequence of the final else part. The general form of the if statement is given below: if ( Expression1 ) { Statement1a Statement1b ... } else if ( Expression2 ) { Statement2a Statement2b ... } else if ( Expression3 ) { Statement3a Statement3b ... } else { Statement4a Statement4b ... } The following example demonstrates conditional execution based on if-else-if statement condition. public class ElseIf { public static void main(String args[]){ int die=4; if (die == 1){ System.out.println("I"); } else if (die == 2){ System.out.println("II"); } else if (die == 3){

System.out.println("III"); } else if (die == 4){ System.out.println("IV"); } else if (die == 5){ System.out.println("V"); } else if (die == 6){ System.out.println("VI"); } else { System.out.println("Something went wrong..."); } }} Output IV

The Switch Case Statements


The switch case statement, also called a case statement is a multi-way branch with several choices. A switch is easier to implement than a series of if/else statements. The switch statement begins with a keyword, followed by an expression that equates to a no long integral value. Following the controlling expression is a code block that contains zero or more labeled cases. Each label must equate to an integer constant and each must be unique. When the switch statement executes, it compares the value of the controlling expression to the values of each case label. The program will select the value of the case label that equals the value of the controlling expression and branch down that path to the end of the code block. If none of the case label values match, then none of the codes within the switch statement code block will be executed. Java includes a default label to use in cases where there are no matches. We can have a nested switch within a case block of an outer switch. The general form of a switch statement is given below: switch(expression){ case val1: code_block1 case val2: code_block2 . . . default: code_default; } The break statement is used within the code block attached to the switch statement to terminate a statement sequence. Therefore, if you want to exit in the middle of the switch statement code block, you must insert a break statement, which causes the program to continue executing after the current code block. The argument to the switch must be an integral expression that must evaluate to a 32-bit or smaller integer type: byte,short,char,or int. Moreover,the legal range of the argument's data type must cover all the case constants used in the code block. For example,the following code fragment will not compile successfully:

byte b = 10; switch( b ){ case 10 : System.out.print("ten"); break ; case 10 : System.out.print("10") ; break ; } In the given code, the compiler will object to the second appearance of the value 10 in line 6. An appropriate example demonstrating the use of switch case to find the greatest among three numbers is provided below. public class SwitchCaseStatementDemo { public static void main(String[] args) { int a = 10, b = 20, c = 30; int status = -1; if (a > b && a > c) { status = 1; } else if (b > c) { status = 2; } else { status = 3; } switch (status) { case 1: System.out.println("a is the greatest"); break; case 2: System.out.println("b is the greatest"); break; case 3: System.out.println("c is the greatest"); break; default: System.out.println("Cannot be determined"); } } } Output: c is the greatest Of course, you could also implement the same thing with if-then-else statements. 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-thenelse 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.

Iteration Statements in Java


Iteration statements enable program execution to repeat one or more statements, i.e. iteration statements form loops. In Java, there are three iteration statements: for, while and do. An enhanced for loop has been added in J2SE 5. The for statement The for loop is the most versatile looping construct. It is used to continuously execute a block of code until a particular condition is satisfied. It comprises three parts: initialization, condition and iteration. The initialization portion is generally an expression that sets the value of the loop control variable. The loop control variable acts as a counter and controls the execution of the loop. The initialization portion executes only once. The condition portion must be a boolean expression. It usually tests the loop control variable against a target value and hence works as a loop terminator. The iteration portion is usually an expression that increments or decrements the loop control variable. The general form of the for loop is: for(initialization; condition; iteration) { //body of the loop } All the three components, i.e., initialization, condition and iteration are optional. In case there is only a single statement in the body of the loop, the curly braces can be omitted. The for loop executes in the following three steps: 1. When the loop first starts, the initialization expression control is transferred to step 2. 2. The condition is evaluated. If the condition evaluates to executes and the program control is transferred to evaluates to false, the loop terminates. 3. The iteration expression executes and then the control is is executed and then the true, the body of the loop step 3. If the condition transferred to step 2.

All the sections in the for-header are optional. Any one of them can be left empty, but the two semicolons are mandatory. In particular, leaving out the <condition> signifies that the loop condition is true. The (;;) form of for loop is commonly used to construct an infinite loop. Below is an example that demonstrates the looping construct namely for loop used to print numbers from 1 to 10. public class ForLoopDemo { public static void main(String[] args) { System.out.println("Printing Numbers from 1 to 10"); for (int count = 1; count <= 10; count++) { System.out.println(count); } } }

Output:

Printing Numbers from 1 to 10 1 2 3 4 5 6 7 8 9 10

The for-each statement


The general form of the for-each loop is as follows: for(type itrvar: collection) { //body of the loop } where, itrvar is the variable that iterates through the elements of the collection. The for-each loop is an enhanced for loop, used to iterate over arrays and collections. This feature is added to Java to make the access and retrieval of elements of arrays and collections faster. The EnhancedForDemo.java program, uses the enhanced for to loop through the array and produces the same output as shown in the previous example: class EnhancedForDemo { public static void main(String[] args){ int[] numbers = {1,2,3,4,5,6,7,8,9,10}; System.out.println("Printing Numbers from 1 to 10"); for (int item : numbers) { System.out.println(item); } } }

The While Statement


The while statement is a looping construct control statement that executes a block of code while a condition is true. You can either have a single statement or a block of code within the while loop. The loop will never be executed if the testing expression evaluates to false. The loop condition must be a boolean expression. The general form of the while loop is as follows: while(condition) { block } where, the condition may be any expression that evaluates to a boolean value. The code block attached to the while statement is repeatedly executed unless the condition

evaluates to false. Below is an example that demonstrates the looping construct namely while loop used to print numbers from 1 to 10. public class WhileLoopDemo { public static void main(String[] args) { int count = 1; System.out.println("Printing Numbers from 1 to 10"); while (count <= 10) { System.out.println(count++); } } } You can implement an infinite loop using the while statement as follows: while (true) { // your code goes here }

Do-while Loop Statement


This statement is similar to the while statement discussed above. The only difference in this case is that the code block attached to the do statement is executed before the condition is checked. Therefore, even in the case of the condition evaluating to false, the code block executes at least once. A do-while loop begins with the keyword do, followed by the statements that make up the body of the loop. Finally, the keyword while and the test expression complete the do-while loop. When the loop condition becomes false, the loop is terminated and execution continues with the statement immediately following the loop. You can either have a single statement or a block of code within the do-while loop. The syntax of the do-while loop is do { code_block } while(condition); Below is an example that demonstrates the looping construct namely do-while loop used to print numbers from 1 to 10. public class DoWhileLoopDemo { public static void main(String[] args) { int count = 1; System.out.println("Printing Numbers from 1 to 10"); do { System.out.println(count++); } while (count <= 10); } }

Jump statements
Jump statements are used to unconditionally transfer the program control to another part of the program. Java has three jump statements: break, continue and return.

The break statement


A break statement is used to abort the execution of a loop. The general form of the break statement is given below: break; class BreakDemo { public static void main(String[]s) { int count = 5; while(true) { if(count == 5) { System.out.println("jump out of the while break; }}}}

block");

A break may be used with or without a label. When it is used without a label, it aborts the execution of the innermost switch, for, do, or while statement enclosing the break statement. When used with a label, the break statement aborts the execution of any enclosing statement matching the label. When used with a label the syntax is: break label; Note: A label is an identifier that uniquely identifies a block of code.

The continue statement


A continue statement stops the iteration of a loop (while, do or for) and causes execution to resume at the top of the nearest enclosing loop. You use a continue statement when you do not want to execute the remaining statements in the loop, but you do not want to exit the loop itself. The syntax of the continue statement is continue; // the unlabeled form continue <label>; // the labeled form You can also provide a loop with a label and then use the label in your continue statement. The label name is optional, and is usually only used when you wish to return to the outermost loop in a series of nested loops. Below is a program to demonstrate the use of continue statement to print Odd Numbers between 1 to 10. public class ContinueExample { public static void main(String[] args) { System.out.println("Odd Numbers"); for (int i = 1; i <= 10; ++i) { if (i % 2 == 0) continue; // Rest of loop body skipped when i is even

} } } Output Odd Numbers 1 3 5 7 9

System.out.println(i + "\t");

The return statement


A return statement is used to transfer the program control to the caller of a method. The general form of the return statement is given below: return expression; If the method is declared to return a value, the expression used after the return statement must evaluate to the return type of that method. Otherwise, the expression is omitted. To return a value, simply put the value (or an expression that calculates the value) after the return keyword. return ++count;

Summary:
This chapter has covered many of the details having to do with Control Statements. By now, you should know that the use of if, else, switch, case, for, while, do, break, continue and return. After a thorough review of the chapter you should be able to know that: Statements that control the flow of the program are called control statements Java, control statements can be divided under three categories: Selection statements, Iteration statements, Jump statements Selection statements are used in a program to choose different paths of execution based upon the outcome of an expression Iteration statements enable program execution to repeat one or more statements Jump statements are used to unconditionally transfer the program control to another part of the program The if statement is a conditional statement. It is used to execute a statement or group of statements based on some condition. The switch statement is used to select multiple alternative execution paths depending on the value of a variable or expression For, while and do statements are used to continuously execute a block of code until a particular condition is satisfied. A break statement is used to abort the execution of a loop. A continue statement is used to alter the execution of the for, do, and while statements. A return statement is used to transfer the program control to the caller of a method.

You might also like