# CONTROL STATEMENTS

&#x20;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:

&#x20;1\) Selection.&#x20;

2\) Iteration.

&#x20;3\) Jump.&#x20;

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.

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

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

#### &#x20;                                                   Selection Statements

&#x20;Java supports two selection statements:

&#x20;A) If

&#x20;B) switch.

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

conditions known only during run time.&#x20;

A) I. If:

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

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

&#x20;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.

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

&#x20;In no case will both statements be executed.

&#x20;**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.

![](https://106491783-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LTW0eWU2biq082hmKEn%2F-LTaX5qmruKnTFVusPx0%2F-LTaSMC-QGsZANZPW_qi%2Fimage.png?alt=media\&token=968e3299-5d41-4e08-9a61-e2fda95ddf70)

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

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

&#x20;Syntax: if(condition) statement; else if(condition) statement; else if(condition) statement; … else statement;

&#x20;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.

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

![](https://106491783-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LTW0eWU2biq082hmKEn%2F-LTaX5qmruKnTFVusPx0%2F-LTaSxb8a4-L6tR1gTYq%2Fimage.png?alt=media\&token=de394473-429f-4718-87af-50bddaea11b3)

#### &#x20;Output:

&#x20;April is in the Spring.&#x20;

**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:

![](https://106491783-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LTW0eWU2biq082hmKEn%2F-LTaX5qmruKnTFVusPx0%2F-LTaTHjd_fMmhqG2nq-k%2Fimage.png?alt=media\&token=0a3433f7-1058-4e7f-a83a-78b5bfaa4fd8)

&#x20;**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.

&#x20;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.&#x20;

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

&#x20;2\) If a match is found, the code sequence following that case statement is executed.

&#x20;3\) If none of the constants matches the value of the expression, then the default statement is executed.

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

**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:**&#x41; simple example of the switch.

![](https://106491783-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LTW0eWU2biq082hmKEn%2F-LTaX5qmruKnTFVusPx0%2F-LTaTvUadXd5JqilaKAl%2Fimage.png?alt=media\&token=91f8d627-64c8-4394-99d0-c1eb5bde47df)

#### &#x20;Output:

i is zero.

&#x20;i is one.&#x20;

i is two.

&#x20;i is three.

&#x20;i is greater than&#x20;

3\. i is greater than 3.&#x20;

**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:

![](https://106491783-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LTW0eWU2biq082hmKEn%2F-LTaX5qmruKnTFVusPx0%2F-LTaUWpqPAm_XecI2KZm%2Fimage.png?alt=media\&token=094fe330-f8a9-478f-9358-5b5d5518c651)

&#x20;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.

&#x20;**Summary:** There are three important features of the switch statement to note:

&#x20;• 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.

&#x20;• 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.

&#x20;• A switch statement is usually more efficient than a set of nested ifs.

#### &#x20;                                                               Iteration Statements

&#x20;Java’s iteration statements are

&#x20;1\) for&#x20;

2\) while&#x20;

3\) do-while.

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

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

&#x20;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.

&#x20;**Example:** while loop that counts down from 10, printing exactly ten lines of “tick”:

![](https://106491783-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LTW0eWU2biq082hmKEn%2F-LTaX5qmruKnTFVusPx0%2F-LTaVRLhYQXSSlmHi4ZB%2Fimage.png?alt=media\&token=c01c032d-553a-4118-a4e9-38a5aafc8526)

#### &#x20;Output:&#x20;

tick 10&#x20;

tick 9

tick 8&#x20;

tick 7&#x20;

tick 6

&#x20;tick 5&#x20;

tick 4&#x20;

tick 3

&#x20;tick 2

&#x20;tick 1

&#x20;**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.

&#x20;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:

![](https://106491783-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LTW0eWU2biq082hmKEn%2F-LTaX5qmruKnTFVusPx0%2F-LTaW0ox6lIS6B_TALek%2Fimage.png?alt=media\&token=5ffb7e93-0a44-48e2-add1-2d1a44a95e8d)

> &#x20;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.

![](https://106491783-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LTW0eWU2biq082hmKEn%2F-LTaX5qmruKnTFVusPx0%2F-LTaZcpfi_OQPbhAaytI%2Fimage.png?alt=media\&token=89b41b6d-6a68-463c-8f49-f678d2a5dcd9)

&#x20;**Output:** i is : 0 i is : 1 i is : 2 i is : 3 i is : 4

&#x20;**3)for:** Beginning with JDK 5, there are two forms of the for loop

&#x20;**A)** “for” form.

&#x20;**B)** “for-each” form. Syntax:

#### &#x20;3. A) for loop:

&#x20;**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.

&#x20;**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.&#x20;

**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.

![](https://106491783-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LTW0eWU2biq082hmKEn%2F-LTaX5qmruKnTFVusPx0%2F-LTaaMtTW9dEg2o5Pd8j%2Fimage.png?alt=media\&token=d2517b85-858c-479c-b0a5-4e26e2c2557d)

&#x20;   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:

&#x20;                                          for(type itr-var : collection)&#x20;

&#x20;                                           statement-block

&#x20;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.&#x20;

NOTE: 1. Enhanced for loop was designed in JDK 1.5.&#x20;

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

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

4\. Enhanced for loop can be used only for arrays and collections.&#x20;

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:

&#x20;for(arraytype varaible : Arrayreference) { }

![](https://106491783-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LTW0eWU2biq082hmKEn%2F-LTaX5qmruKnTFVusPx0%2F-LTabFmdIDV2hSU75wd9%2Fimage.png?alt=media\&token=4ca32037-bbc8-44e4-a020-5dfdba65b253)

&#x20;**Output:** Value is: 1 Value is: 2&#x20;

Value is: 3 Value is: 4

&#x20;Value is: 5 Value is: 6&#x20;

Value is: 7 Summation: 28

![](https://106491783-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LTW0eWU2biq082hmKEn%2F-LTaX5qmruKnTFVusPx0%2F-LTaba9ojT0vNkyOTv6-%2Fimage.png?alt=media\&token=f74087d5-841f-4205-9f68-0192bc2f219d)

#### &#x20;Output:&#x20;

Value is: 1&#x20;

Value is: 2

&#x20;Value is: 3

&#x20;Value is: 4

&#x20;Value is: 5

&#x20;Summation of first 5 elements: 15

&#x20;**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:

![](https://106491783-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LTW0eWU2biq082hmKEn%2F-LTaX5qmruKnTFVusPx0%2F-LTac0b1VZupBs_uP-rP%2Fimage.png?alt=media\&token=39d7aa89-6f5a-4d3d-9776-b5e1399d932d)

#### &#x20;                                        Jump Statements

&#x20;Java supports three jump statements:&#x20;

A) break.

&#x20;B) continue.

&#x20;C) return.&#x20;

These statements transfer control to another part of your program.

&#x20;**A) break:** In Java, the break statement has three uses.

&#x20;1\)It terminates a statement sequence in a switch statement.

&#x20;2\)It can be used to exit a loop.&#x20;

3\)It can be used as a “civilized” form of goto.&#x20;

**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.

![](https://106491783-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LTW0eWU2biq082hmKEn%2F-LTaX5qmruKnTFVusPx0%2F-LTad2h_3Rvnvb67v6yL%2Fimage.png?alt=media\&token=ee9aa8e3-d04d-4963-bba6-aa2162c83545)

&#x20;**Output:** i: 0 i: 1 i: 2 i: 3 i: 4 i: 5 i: 6 i: 7 i: 8 i: 9

&#x20;Loop complete.&#x20;

**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.

![](https://106491783-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LTW0eWU2biq082hmKEn%2F-LTaX5qmruKnTFVusPx0%2F-LTadRKShzjdFq2uPvGZ%2Fimage.png?alt=media\&token=742c7509-ab68-4709-abd8-21c1ae95984d)

![](https://106491783-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LTW0eWU2biq082hmKEn%2F-LTaX5qmruKnTFVusPx0%2F-LTad_46HxqOtaRp5HSB%2Fimage.png?alt=media\&token=e26272a0-9c0f-43fe-96d6-1776087de70c)

&#x20;**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.

&#x20;**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.

&#x20;**3) Using break as a Form of Goto**:&#x20;

**Syntax:** break label;

![](https://106491783-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LTW0eWU2biq082hmKEn%2F-LTaX5qmruKnTFVusPx0%2F-LTae0Q6NXLcXhMoz3A_%2Fimage.png?alt=media\&token=ec8ea6b8-41e0-4d7f-aab0-ca189cda599f)

&#x20;**Output:** Before the break.&#x20;

This is after second block.

![](https://106491783-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LTW0eWU2biq082hmKEn%2F-LTaX5qmruKnTFVusPx0%2F-LTaeGCt9rZMuWpJ5YJV%2Fimage.png?alt=media\&token=c670478f-7ec0-4054-8113-75b776527c6e)

&#x20;**Output:** Pass 0: 0 1 2 3 4 5 6 7 8 9 Loops complete.

&#x20;**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.

![](https://106491783-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LTW0eWU2biq082hmKEn%2F-LTaX5qmruKnTFVusPx0%2F-LTaeV_EqWgknnOi6ZNY%2Fimage.png?alt=media\&token=74bfe659-cea4-40ce-94dd-8edb8b8fd10d)

&#x20;**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

&#x20;**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.

![](https://106491783-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LTW0eWU2biq082hmKEn%2F-LTaX5qmruKnTFVusPx0%2F-LTaelg7wZIYHpRUWmOz%2Fimage.png?alt=media\&token=0b19b3cf-590c-4229-89f2-8afa7d7630db)

