Unit-5-Control-Statements
Unit-5-Control-Statements
com
Unit-5/ Java Programming - I
Only one statement can appear directly after the if or the else. If you wan to include more
statements, you’ll need to create a block.
The Nested ifs
A nested if is an if statement that is the target of another if or else. Nested ifs are very
common in programming. When you nest ifs, the main thing to remember is that an else
https://genuinenotes.com
https://genuinenotes.com
Unit-5/ Java Programming - I
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 is an example:
Example:
https://genuinenotes.com
https://genuinenotes.com
Unit-5/ Java Programming - I
The if statements are executed from the top 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.
public class IfElseIfExample {
https://genuinenotes.com
https://genuinenotes.com
Unit-5/ Java Programming - I
Here expression can be of type byte, short, int, char, enumeration or String
Each value specified in the case statements must be a unique constant expression (such as
a literal value). Duplicate case values are not allowed. The type of each value must be
compatible with the type of expression.
The switch statement works like this: The value of the expression is compared with each
of the values in the case statements. If a match is found, the code sequence following that
case statement is executed. If none of the constants matches the value of the expression,
then the default statement is executed. However, the default statement is optional. If no
case matches and no default is present, then no further action is taken.
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.
The break statement is optional. If you omit the break, execution will continue on into
the next case. It is sometimes desirable to have multiple cases without break statements
between them.
https://genuinenotes.com
https://genuinenotes.com
Unit-5/ Java Programming - I
Example:
class Day {
public static void main(String[] args) {
int week = 4;
String day;
switch (week) {
case 1:
day = "Sunday";
break;
case 2:
day = "Monday";
break;
case 3:
day = "Tuesday";
break;
case 4:
day = "Wednesday";
break;
case 5:
day = "Thursday";
break;
case 6:
day = "Friday";
break;
case 7:
day = "Saturday";
break;
default:
day = "Invalid day";
break;
}
System.out.println(day);
}
}
https://genuinenotes.com
https://genuinenotes.com
Unit-5/ Java Programming - I
Note:
The switch differs from the if in 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.
https://genuinenotes.com
https://genuinenotes.com
Unit-5/ Java Programming - I
Iteration Statements
Java’s iteration statements are for, while, and do-while. These statements create what we
commonly call loops. As you probably know, a loop repeatedly executes the same set of
instructions until a termination condition is met.
The while loop
The while loop is Java’s most fundamental loop statement. It repeats a statement or block
while its controlling expression is true. Here is its general form:
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.
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.
Example:
class WhileLoopExample {
public static void main(String args[]){
int i=10;
while(i>1){
System.out.println(i);
i--;
}
}
}
The body of the while (or any other of Java’s loops) can be empty. This is because a null
statement (one that consists only of a semicolon) is syntactically valid in Java.
The following program is an example for this fact.
https://genuinenotes.com
https://genuinenotes.com
Unit-5/ Java Programming - I
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.
Example:
class DoWhileLoopExample {
public static void main(String args[]){
int arr[]={2,11,45,9};
//i starts with 0 as array index starts with 0
int i=0;
do{
System.out.println(arr[i]);
i++;
}while(i<4);
}
}
https://genuinenotes.com
https://genuinenotes.com
Unit-5/ Java Programming - I
Example:
public class ForLoopExample {
public static void main(String args[]){
for(int i=1; i<=10; i++){
System.out.println("7 * "+i+" = "+ 7*i);
}
}
}
https://genuinenotes.com
https://genuinenotes.com
Unit-5/ Java Programming - I
In this example, the for loop continues to run until the boolean variable done is set to true. It
does not test the value of i.
Here is another interesting for loop variation. Either the initialization or the iteration
expression or both may be absent, as in this next program:
Here, the initialization and iteration expressions have been moved out of the for. Thus, parts of
the for are empty. While this is of no value in this simple example—indeed, it would be
considered quite poor style—there can be times when this type of approach makes sense. For
example, if the initial condition is set through a complex expression elsewhere in the program or
if the loop control variable changes in a nonsequential manner determined by actions that occur
within the body of the loop, it may be appropriate to leave these parts of the for empty.
https://genuinenotes.com
https://genuinenotes.com
Unit-5/ Java Programming - I
Here is one more for loop variation. You can intentionally create an infinite loop (a loop
that never terminates) if you leave all three parts of the for empty. For example:
This loop will run forever because there is no condition under which it will terminate. Although
there are some programs, such as operating system command processors,that require an infinite
loop, most “infinite loops” are really just loops with special termination requirements.
https://genuinenotes.com
https://genuinenotes.com
Unit-5/ Java Programming - I
https://genuinenotes.com
https://genuinenotes.com
Unit-5/ Java Programming - I
https://genuinenotes.com
https://genuinenotes.com
Unit-5/ Java Programming - I
The following program uses a traditional for loop to compute the sum of the values in an array:
public class Sum {
public static void main(String[] args){
int numbers[] = {1,2,3,4,5,6,7,8,9,10};
int sum=0;
for(int i =0;i<numbers.length;i++){
sum+=numbers[i];
}
System.out.println("The sum of elements of the array is= "+sum);
}
}
The following program uses for each style loop to compute the sum of elements of an array:
public class ForEachDemo {
public static void main(String[] args){
int numbers[] = {1,2,3,4,5,6,7,8,9,10};
int sum=0;
//using for-each style loop
for(int x: numbers){
sum+=x;
}
System.out.println("The sum of elements of the array is= "+sum);
}
}
https://genuinenotes.com
https://genuinenotes.com
Unit-5/ Java Programming - I
In summary:
It starts with the keyword for like a normal for-loop.
Instead of declaring and initializing a loop counter variable, we declare a variable that is
the same type as the base type of the array, followed by a colon, which is then followed
by the array name.
In the loop body, we can use the loop variable we created rather than using an indexed
array element.
It’s commonly used to iterate over an array or a Collections class (eg, ArrayList)
Limitations of for-each loop
For-each loops are not appropriate when we want to modify the array:
For-each loops do not keep track of index. So we cannot obtain array index using For-
Each loop
For-each only iterates forward over the array in single steps
Iterating Over Multidimensional Arrays
The enhanced version of the for also works on multidimensional arrays.
When using the for-each for to iterate over an array of N dimensions, the objects obtained
will be arrays of N–1 dimensions. For example, in the case of a two dimensional array,
the iteration variable must be a reference to a one-dimensional array
Example:
https://genuinenotes.com
https://genuinenotes.com
Unit-5/ Java Programming - I
https://genuinenotes.com
https://genuinenotes.com
Unit-5/ Java Programming - I
Nested Loops
Like all other programming languages, Java allows loops to be nested. That is, one loop may be
inside another.
public class PatternExample {
public static void main(String[] args){
for(int i = 1;i<5;i++){
for(int j=i;j<5;j++){
System.out.print("+");
}
System.out.println();
}
}
}
Jump Statements
Java supports different jump statements. break, continue are two of them.
Using break
In Java, the break statement has three uses.
1. To terminate 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.
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.
The break statement can be used with any of Java’s loops, including intentionally infinite
loops.
The break statement in the inner loop only causes termination of that loop. The outer
loop is unaffected.
https://genuinenotes.com
https://genuinenotes.com
Unit-5/ Java Programming - I
https://genuinenotes.com
https://genuinenotes.com
Unit-5/ Java Programming - I
Output:
1
2
3
4
Note: Here are two other points to remember about break. First, more than one break statement
may appear in a loop. However, be careful. Too many break statements have the tendency to
destructure your code. Second, the break that terminates a switch statement affects only that
switch statement and not any enclosing loops.
https://genuinenotes.com
https://genuinenotes.com
Unit-5/ Java Programming - I
Most often, label is the name of a label that identifies a block of code. This can be a
standalone block of code but it can also be a block that is the target of another statement.
When this form of break executes, control is transferred out of the named block. The
labeled block must enclose the break statement, but it does not need to be the
immediately enclosing block. This means, for example, that you can use a labeled break
statement to exit from a set of nested blocks. But you cannot use break to transfer control
out of a block that does not enclose the break statement.
To name a block, put a label at the start of it. A label is any valid Java identifier followed by a
colon. Once you have labeled a block, you can then use this label as the target of a break
statement.
Example:
class LabeledBreak {
public static void main(String[] args) {
first:
for( int i = 1; i < 5; i++) {
second:
for(int j = 1; j < 3; j ++ ) {
System.out.println("i = " + i + "; j = " +j);
https://genuinenotes.com
https://genuinenotes.com
Unit-5/ Java Programming - I
if ( i == 2)
break first;
}
}
}
}
Another Example:
Using continue
Sometimes it is useful to force an early iteration of a loop. That is, you might want to continue
running the loop but stop processing the remainder of the code in its body for this particular
iteration. This is, in effect, a goto just past the body of the loop, to the loop’s end. The continue
statement performs such an action. 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.
The continue statement is used in loop control structure when you need to jump to the
next iteration of the loop immediately.
The Java continue statement is used to continue the loop. It continues the current flow of
the program and skips the remaining code at the specified condition.
In a for loop, the continue keyword causes control to immediately jump to the update
statement.
In a while loop or do/while loop, control immediately jumps to the Boolean expression.
https://genuinenotes.com
https://genuinenotes.com
Unit-5/ Java Programming - I
As with the break statement, continue may specify a label to describe which enclosing
loop to continue.
Example:
class Test {
public static void main(String[] args) {
https://genuinenotes.com
https://genuinenotes.com
Unit-5/ Java Programming - I
Output:
1
2
3
4
9
10
Output:
1 1
1 2
1 3
2 1
3 1
3 2
3 3
Good uses of continue are rare. One reason is that Java provides a rich set of loop statements
which fit most applications. However, for those special circumstances in which early iteration is
needed, the continue statement provides a structured way to accomplish it.
https://genuinenotes.com