CONTROL STATEMENTS

Java Control statements in a programming language are very useful as they allow a programmer to change the flow of program execution i.e. altering the normal program flow to jump directly on some statement or to skip a statement. Java’s program control statements can be put into the following categories:

1) Selection.

2) Iteration.

3) Jump.

1) Selection statements: allow your program to choose different paths of execution based upon the outcome of an expression or the state of a variable.

2) Iteration statements: enable program execution to repeat one or more statements (that is, iteration statements form loops).

3) Jump statements: allow your program to execute in a nonlinear fashion.

Selection Statements

Java supports two selection statements:

A) If

B) switch.

These statements allow you to control the flow of your program’s execution based upon

conditions known only during run time.

A) I. If:

The 'if' statement is Java’s conditional branch statement. It can be used to route program execution Syntax:

if (condition){ statement1; } Else{ statement2;

Here each statement may be a single statement or a compound statement enclosed in curly braces (that is, a block). The condition is any expression that returns a boolean value. The else clause is optional.

Working: If the condition is true, then statement1 is executed. Otherwise, statement2 (if it exists) is executed.

In no case will both statements be executed.

A) II. Nested ifs: A nested if is an if statement that is the target of another if or else. When you nest ifs, the main thing to remember is that an else statement always refers to the nearest if statement that is within the same block as the else and that is not already associated with an else.

Here, as the comments indicate, the final else is not associated with if(j100) because it is the closest if within the same block.

A) III. if-else-if Ladder: A common programming construct that is based upon a sequence of nested ifs is the if-else-if ladder

Syntax: if(condition) statement; else if(condition) statement; else if(condition) statement; … else statement;

Here 'if' statements are executed from top to down. As soon as one of the conditions controlling the 'if' is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed. The final else acts as a default condition; that is, if all other conditional tests fail, then the last else statement is performed.

If there is no final else and all other conditions are false, then no action will take place.

Output:

April is in the Spring.

B) I. switch The switch statement is Java’s multiway branch statement. It provides an easy way to dispatch execution to different parts of your code based on the value of an expression. Syntax:

Rules: 1) The expression must be of type byte, short, int, or char; each of the values specified in the case statements must be of a type compatible with the expression.

2) Each case value must be a unique literal (that is, it must be a constant, not a variable). Duplicate case values are not allowed.

Working: 1) The value of the expression is compared with each of the literal values in the case statements.

2) If a match is found, the code sequence following that case statement is executed.

3) If none of the constants matches the value of the expression, then the default statement is executed.

4) However, the default statement is optional. If no case matches and no default is present, then no further action is taken.

Note: The break statement is used inside the switch to terminate a statement sequence. When a break statement is encountered, execution branches to the first line of code that follows the entire switch statement. This has the effect of “jumping out” of the switch. Example:A simple example of the switch.

Output:

i is zero.

i is one.

i is two.

i is three.

i is greater than

3. i is greater than 3.

B) II. Nested switch Statements: You can use a switch as part of the statement sequence of an outer switch. This is called a nested switch. Since a switch statement defines its own block, no conflicts arise between the case constants in the inner switch and those in the outer switch. Syntax:

Here, the case 1: statement in the inner switch does not conflict with the case 1: statement in the outer switch. The count variable is only compared with the list of cases at the outer level. If count is 1, then target is compared with the inner list cases.

Summary: There are three important features of the switch statement to note:

• The switch differs from the 'if', that switch can only test for equality, whereas if can evaluate any type of Boolean expression. That is, the switch looks only for a match between the value of the expression and one of its case constants.

• No two case constants in the same switch can have identical values. Of course, a switch statement and an enclosing outer switch can have case constants in common.

• A switch statement is usually more efficient than a set of nested ifs.

Iteration Statements

Java’s iteration statements are

1) for

2) while

3) do-while.

These statements create what we commonly call loops. A loop repeatedly executes the same set of instructions until a termination condition is met.

1) while: It repeats a statement or block while its controlling expression is true. Syntax:

Here, The condition can be any Boolean expression. The body of the loop will be executed as long as the conditional expression is true. When condition becomes false, control passes to the next line of code immediately following the loop. The curly braces are unnecessary if only a single statement is being repeated.

Example: while loop that counts down from 10, printing exactly ten lines of “tick”:

Output:

tick 10

tick 9

tick 8

tick 7

tick 6

tick 5

tick 4

tick 3

tick 2

tick 1

Note: Since the while loop evaluates its conditional expression at the top of the loop, the body of the loop will not execute even once if the condition is false to begin with.

2) do-while: The do-while loop always executes its body at least once, because its conditional expression is at the bottom of the loop. Syntax:

Note: Each iteration of the do-while loop first executes the body of the loop and then evaluates the conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop terminates. As with all of Java’s loops, condition must be a Boolean expression.

Output: i is : 0 i is : 1 i is : 2 i is : 3 i is : 4

3)for: Beginning with JDK 5, there are two forms of the for loop

A) “for” form.

B) “for-each” form. Syntax:

3. A) for loop:

1) When the loop first starts, the initialization portion of the loop is executed. Generally, this is an expression that sets the value of the loop control variable, which acts as a counter that controls the loop. It is important to understand that the initialization expression is only executed once.

2) Next, condition is evaluated. This must be a Boolean expression. It usually tests the loop control variable against a target value. If this expression is true, then the body of the loop is executed. If it is false, the loop terminates.

3) Next, the iteration portion of the loop is executed. This is usually an expression that increments or decrements the loop control variable. The loop then iterates, first evaluating the conditional expression, then executing the body of the loop, and then executing the iteration expression with each pass. This process repeats until the controlling expression is false.

A for-each style loop is designed to cycle through a collection of objects, such as an array, in strictly sequential fashion, from start to finish. The advantage of this approach is that no new keyword is required, and no preexisting code is broken. Syntax:

for(type itr-var : collection)

statement-block

Here,type specifies the type itr-var specifies the name of an iteration variable that will receive the elements from a collection, one at a time, from beginning to end. The collection being cycled through is specified by collection. With each iteration of the loop, the next element in the collection is retrieved and stored in itr-var. The loop repeats until all elements in the collection have been obtained. Because the iteration variable receives values from the collection, type must be the same as (or compatible with) the elements stored in the collection. Thus, when iterating over arrays, type must be compatible with the base type of the array.

NOTE: 1. Enhanced for loop was designed in JDK 1.5.

2. To fetch the element stored in array and collections without any condition, we can use extended for loop.

3. Enhanced for loop is also called as ”for-each” loop because each and every element will be fetched without fail.

4. Enhanced for loop can be used only for arrays and collections.

5. If you want to perform a common operation on all the elements stored in a array or collection then best approach is using enhanced for loop Syntax:

for(arraytype varaible : Arrayreference) { }

Output: Value is: 1 Value is: 2

Value is: 3 Value is: 4

Value is: 5 Value is: 6

Value is: 7 Summation: 28

Output:

Value is: 1

Value is: 2

Value is: 3

Value is: 4

Value is: 5

Summation of first 5 elements: 15

3. C) Nested loops: Like all other programming languages, Java allows loops to be nested. That is, one loop may be inside another. For example, here is a program that nests for loops:

Jump Statements

Java supports three jump statements:

A) break.

B) continue.

C) return.

These statements transfer control to another part of your program.

A) break: In Java, the break statement has three uses.

1)It terminates a statement sequence in a switch statement.

2)It can be used to exit a loop.

3)It can be used as a “civilized” form of goto.

2) Using break to Exit a Loop: By using break, you can force immediate termination of a loop, bypassing the conditional expression and any remaining code in the body of the loop. When a break statement is encountered inside a loop, the loop is terminated and program control resumes at the next statement following the loop.

Output: i: 0 i: 1 i: 2 i: 3 i: 4 i: 5 i: 6 i: 7 i: 8 i: 9

Loop complete.

Working: Although for loop is designed to run from 0 to 99, the break statement causes it to terminate early, when i equals 10. The break statement can be used with any of Java’s loops, including intentionally infinite loops.

Output: Pass 1: 0 1 2 3 4 5 6 7 8 9 Pass 2: 0 1 2 3 4 5 6 7 8 9 Loops complete.

Points to remember: First, more than one break statement may appear in a loop. However, be careful. Too many break statements have the tendency to destruct your code. Second, the break that terminates a switch statement affects only that switch statement and not any enclosing loops.

3) Using break as a Form of Goto:

Syntax: break label;

Output: Before the break.

This is after second block.

Output: Pass 0: 0 1 2 3 4 5 6 7 8 9 Loops complete.

B) continue: In while and do-while loops, a continue statement causes control to be transferred directly to the conditional expression that controls the loop. In a for loop, control goes first to the iteration portion of the for statement and then to the conditional expression. For all three loops, any intermediate code is bypassed.

Output: 0 0 1 0 2 4 0 3 6 9 0 4 8 12 16 0 5 10 15 20 25 0 6 12 18 24 30 36 0 7 14 21 28 35 42 49 0 8 16 24 32 40 48 56 64 0 9 18 27 36 45 54 63 72 81

C) return: The return statement is used to explicitly return from a method. That is, it causes program control to transfer back to the caller of the method. At any time in a method the return statement can be used to cause execution to branch back to the caller of the method. Thus, the return statement immediately terminates the method in which it is executed.

Last updated