Lecture 3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 51

Lecture 3:

Selections, Repetition

Object Oriented Programming


1
Control Flow Statements
• There are two types of decision making statements in Java. They
are:
– ‘if’
– ‘switch’ statements.

• There may be a situation when we need to execute a block of code


several number of times and is often referred to as a loop/iteration.
Java has very flexible three looping mechanisms. You can use one
of the following three loops:
– while Loop
– do...while Loop
– for Loop

• When we need to execute a set of statements based on a


condition then we need to use control flow statements.
2
Control Flow Statements

• For example, if a number is greater than zero then we want to print


“Positive Number” but if it is less than zero then we want to print
“Negative Number”.

• In this case we have two print statements in the program, but only
one print statement executes at a time based on the input value.
We will see how to write such type of conditions in the java
program using control statements.

3
if statement

4
If Statements
• In this lecture, we will see four types of control statements that you
can use in java programs based on the requirement:

a) if statement
b) nested if statement
c) if-else statement
d) if-else-if statement

5
If statement
• If statement consists a condition, followed by statement or a set of
statements as shown below:

if(condition)
{
Statement(s);
}

• The statements gets executed only when the given condition is


true. If the condition is false then the statements inside if statement
body are completely ignored.

6
Example of if statement
public class IfStatementExample {

public static void main(String args[]){


int num=70;
if( num < 100 ){
/* This println statement will only execute,
* if the above condition is true
*/
System.out.println("number is less than 100");
}
}
}
Output:

number is less than 100

7
Nested if statement in Java
• When there is an if statement inside another if statement then it is
called the nested if statement.

• The structure of nested if looks like this:


if(condition_1) {
Statement1(s);

if(condition_2) {
Statement2(s);
}
}

• Statement1 would execute if the condition_1 is true. Statement2


would only execute if both the conditions( condition_1 and
condition_2) are true. 8
Example of Nested if statement
public class NestedIfExample {

public static void main(String args[]){


int num=70;
if( num < 100 ){
System.out.println("number is less than 100");
if(num > 50){
System.out.println("number is greater than 50");
}
}
}
}

Output:
number is less than 100
number is greater than 50

9
If else statement in Java
• This is how an if-else statement looks:

if(condition) {
Statement(s);
}
else {
Statement(s);
}
• The statements inside “if” would execute if the condition is true,
and the statements inside “else” would execute if the condition is
false.

10
Example of if-else statement
public class IfElseExample {

public static void main(String args[]){


int num=120;
if( num < 50 ){
System.out.println("num is less than 50");
}
else {
System.out.println("num is greater than or equal 50");
}
}
}

Output:
num is greater than or equal 50

11
if-else-if Statement
• if-else-if statement is used when we need to check multiple conditions. In
this statement we have only one “if” and one “else”, however we can have
multiple “else if”. It is also known as if else if ladder. This is how it looks:

if(condition_1) {
/*if condition_1 is true execute this*/
statement(s);
}
else if(condition_2) {
/* execute this if condition_1 is not met and condition_2 is met */
statement(s);
}
else if(condition_3) {
/* execute this if condition_1 & condition_2 are not met and condition_3 is met */
statement(s);
}
.
.
.
else {
/* if none of the condition is true then these statements gets executed */
statement(s);
12
}
if-else-if Statement
• Note: The most important point to note here is that in if-else-if statement,
as soon as the condition is met, the corresponding set of statements get
executed, rest gets ignored. If none of the condition is met then the
statements inside “else” gets executed.

13
Example of if-else-if
public class IfElseIfExample {
public static void main(String args[]){
int num=1234;
if(num <100 && num>=1) {
System.out.println("Its a two digit number");
}
else if(num <1000 && num>=100) {
System.out.println("Its a three digit number");
}
else if(num <10000 && num>=1000) {
System.out.println("Its a four digit number");
}
else if(num <100000 && num>=10000) {
System.out.println("Its a five digit number");
}
else {
System.out.println("number is not between 1 & 99999");
}
}
}

Output:
Its a four digit number
14
Switch Case statement in Java
with example

15
Switch Case statement in Java
• Switch case statement is used when we have number of options (or
choices) and we may need to perform a different task for each choice.

• The syntax of Switch case statement looks like this

switch (variable or an integer expression)


{
case constant:
//Java code
;
case constant:
//Java code
;
default:
//Java code
;
}

• Switch Case statement is mostly used with break statement even though it
is optional. We will first see an example without break statement and then
we will discuss switch case with break
16
A Simple Switch Case Example
public class SwitchCaseExample1 {

public static void main(String args[]){


int num=2;
switch(num+2)
{
case 1:
System.out.println("Case1: Value is: "+num);
case 2:
System.out.println("Case2: Value is: "+num);
case 3:
System.out.println("Case3: Value is: "+num);
default:
System.out.println("Default: Value is: "+num);
}
}
}
17
A Simple Switch Case Example
• Output:
Default: Value is: 2

• Explanation: In switch I gave an expression, you can give variable


also. I gave num+2, where num value is 2 and after addition the
expression resulted 4. Since there is no case defined with value 4
the default case got executed. This is why we should use default in
switch case, so that if there is no catch that matches the condition,
the default block gets executed.

18
Break statement in Switch Case
• Break statement is optional in switch case but you would use it almost
every time you deal with switch case. Before we discuss about break
statement, Let’s have a look at the example below where I am not using
the break statement:

public class SwitchCaseExample2 {


public static void main(String args[]){
int i=2;
switch(i)
{
case 1:
System.out.println("Case1 ");
case 2:
System.out.println("Case2 ");
case 3:
System.out.println("Case3 ");
case 4:
System.out.println("Case4 ");
default:
System.out.println("Default ");
}
} 19
}
Break statement in Switch Case
• Output:
Case2
Case3
Case4
Default

• In the above program, we have passed integer value 2 to the


switch, so the control switched to the case 2, however we don’t
have break statement after the case 2 that caused the flow to pass
to the subsequent cases till the end. The solution to this problem is
break statement

20
Break statement in Switch Case
• Break statements are used when you want your program-flow to
come out of the switch body. Whenever a break statement is
encountered in the switch body, the execution flow would directly
come out of the switch, ignoring rest of the cases

• Let’s take the same example but this time with break statement.

21
Example with break statement
public class SwitchCaseExample2 {
public static void main(String args[]){
int i=2;
switch(i)
{
case 1:
System.out.println("Case1 ");
break;
case 2:
System.out.println("Case2 ");
break;
case 3:
System.out.println("Case3 ");
break;
case 4:
System.out.println("Case4 ");
break;
default:
System.out.println("Default ");
}
} 22
}
Example with break statement
• Output:
Case2

• Now you can see that only case 2 had been executed, rest of the
cases were ignored.

• Why didn’t I use break statement after default?


• The control would itself come out of the switch after default so I
didn’t use it, however if you still want to use the break after default
then you can use it, there is no harm in doing that.

23
Few points about Switch Case
• 1) Case doesn’t always need to have order 1, 2, 3 and so on. It can
have any integer value after case keyword. Also, case doesn’t
need to be in an ascending order always, you can specify them in
any order based on the requirement.

24
Few points about Switch Case
• 2) You can also use characters in switch case. for example –

public class SwitchCaseExample2 {


public static void main(String args[]){
char ch='b';
switch(ch)
{
case 'd':
System.out.println("Case1 ");
break;
case 'b':
System.out.println("Case2 ");
break;
case 'x':
System.out.println("Case3 ");
break;
case 'y':
System.out.println("Case4 ");
break;
default:
System.out.println("Default ");
}
} 25
}
Few points about Switch Case
• 3) The expression given inside switch should result in a constant
value otherwise it would not be valid.
– For example:
– Valid expressions for switch:
• switch(1+2+23)
• switch(1*2+3%4)

– Invalid switch expressions:


• switch(ab+cd)
• switch(a+b+c)

• 4) Nesting of switch statements are allowed, which means you can


have switch statements inside another switch. However nested
switch statements should be avoided as it makes program more
complex and less readable.
26
loop/iteration
• There may be a situation when we need to execute a block of code
several number of times and is often referred to as a loop/iteration.
Java has very flexible three looping mechanisms. You can use one
of the following three loops:

– while Loop
– do...while Loop
– for Loop

27
For loop in Java with example

28
For loop in Java
• Loops are used to execute a set of statements repeatedly until a
particular condition is satisfied. In Java we have three types of
basic loops: for, while and do-while. In this tutorial we will learn
how to use “for loop” in Java.

• Syntax of for loop:


for(initialization; condition ; increment/decrement)
{
statement(s);
}

29
Flow of Execution of the for Loop
• As a program executes, the interpreter always keeps track of which
statement is about to be executed. We call this the control flow, or the flow
of execution of the program.
• First step: In for loop, initialization happens first and only one time, which
means that the initialization part of for loop only executes once.

• Second step: Condition in for loop is evaluated on each iteration, if the


condition is true then the statements inside for loop body gets executed.
Once the condition returns false, the statements in for loop does not
execute and the control gets transferred to the next statement in the
program after for loop.

• Third step: After every execution of for loop’s body, the


increment/decrement part of for loop executes that updates the loop
counter.

• Fourth step: After third step, the control jumps to second step and
30
condition is re-evaluated.
Example of Simple For loop

• The output of this program is:


class ForLoopExample {
public static void main(String args[]){
The value of i is: 10
for(int i=10; i>1; i--){
The value of i is: 9
System.out.println("The value of i is: "+i);
The value of i is: 8
}
The value of i is: 7
}
The value of i is: 6
}
The value of i is: 5
The value of i is: 4
The value of i is: 3
The value of i is: 2

31
Example of Simple For loop
• In the above program:
– int i=1 is initialization expression
– i>1 is condition(Boolean expression)
– i– Decrement operation

32
Infinite for loop
• The importance of Boolean expression and increment/decrement
operation co-ordination:

class ForLoopExample2 {
public static void main(String args[]){
for(int i=1; i>=1; i++){
System.out.println("The value of i is: "+i);
}
}
}

• This is an infinite loop as the condition would never return false.


• The initialization step is setting up the value of variable i to 1, since we are
incrementing the value of i, it would always be greater than 1 (the Boolean
expression: i>1) so it would never return false.

• This would eventually lead to the infinite loop condition.


33
Infinite for loop
• This would eventually lead to the infinite loop condition. Thus it is
important to see the co-ordination between Boolean expression
and increment/decrement operation to determine whether the loop
would terminate at some point of time or not.

• Here is another example of infinite for loop:

// infinite loop
for ( ; ; ) {
// statement(s)
}

34
While loop in Java with examples

35
While loop in Java
• As above, loops are used to execute a set of statements repeatedly until a
particular condition is satisfied.
• Syntax of while loop
while(condition)
{
statement(s);
}

• How while Loop works?


• In while loop, condition is evaluated first and if it returns true then the
statements inside while loop execute. When condition returns false, the
control comes out of loop and jumps to the next statement after while loop.

• Note: The important point to note when using while loop is that we need to
use increment or decrement statement inside while loop so that the loop
variable gets changed on each iteration, and at some point condition
returns false. This way we can end the execution of while loop otherwise
the loop would execute indefinitely. 36
Simple while loop example

class WhileLoopExample { • Output:


public static void main(String args[]){
int i=10; 10
while(i>1){
9
System.out.println(i);
8
i--;
} 7
} 6
} 5
4
3
2

37
Infinite while loop
class WhileLoopExample2 {
public static void main(String args[]){
int i=10;
while(i>1)
{
System.out.println(i);
i++;
}
}
}
• This loop would never end, its an infinite while loop. This is
because condition is i>1 which would always be true as we are
incrementing the value of i inside while loop.

• Here is another example of infinite while loop:

while (true){
statement(s);
38
}
do-while loop in Java with example

39
do-while loop
• Now we will discuss do-while loop in java. do-while loop is similar to while
loop, however there is a difference between them: In while loop, condition
is evaluated before the execution of loop’s body but in do-while loop
condition is evaluated after the execution of loop’s body.

• Syntax of do-while loop:


do
{
statement(s);
} while(condition);

• How do-while loop works?


• First, the statements inside loop execute and then the condition gets
evaluated, if the condition returns true then the control gets transferred to
the “do” else it jumps to the next statement after do-while.

40
do-while loop example

class DoWhileLoopExample {
public static void main(String args[]){ • Output:
int i=10;
do{ 10
System.out.println(i); 9
i--; 8
}while(i>1);
7
}
6
}
5
4
3
2

41
Continue Statement in Java with example

42
Continue statement
• Continue statement is mostly used inside loops. Whenever it is
encountered inside a loop, control directly jumps to the beginning
of the loop for next iteration, skipping the execution of statements
inside loop’s body for the current iteration. This is particularly
useful when you want to continue the loop but do not want the rest
of the statements(after continue statement) in loop body to execute
for that particular iteration.

• Syntax:
• continue word followed by semi colon.

continue;

43
Example: continue statement inside for
loop
public class ContinueExample {
public static void main(String args[]){
for (int j=0; j<=6; j++)
{
if (j==4)
{
continue;
}
System.out.print(j+" ");
}
}
}
• Output:
012356

• As you may have noticed, the value 4 is missing in the output, why?
because when the value of variable j is 4, the program encountered a
continue statement, which makes it to jump at the beginning of for loop for
next iteration, skipping the statements for current iteration (that’s the
reason println didn’t execute when the value of j was 4). 44
Example: Use of continue in While
loop
• Same thing you can see here. We are iterating this loop from 10 to 0 for
counter value and when the counter value is 7 the loop skipped the print
statement and started next iteration of the while loop.
public class ContinueExample2 {

public static void main(String args[]){


int counter=10;
while (counter >=0)
{
if (counter==7)
{
counter--;
continue;
}
System.out.print(counter+" ");
counter--;
}
}
}

• Output:
10 9 8 6 5 4 3 2 1 0 45
Example of continue in do-While loop
public class ContinueExample3 {
public static void main(String args[]){
int j=0;
do
{
if (j==7)
{
j++;
continue;
}
System.out.print(j+ " ");
j++;
}while(j<10);

}
}

• Output:
012345689 46
Break statement in Java with example

47
Break statement
• The break statement is usually used in following two scenarios:

– a) Use break statement to come out of the loop instantly. Whenever a break
statement is encountered inside a loop, the control directly comes out of loop
and the loop gets terminated for rest of the iterations. It is used along with if
statement, whenever used inside loop so that the loop gets terminated for a
particular condition.

• The important point to note here is that when a break statement is used inside a
nested loop, then only the inner loop gets terminated.

– b) It is also used in switch case control. Generally all cases in switch case are
followed by a break statement so that whenever the program control jumps to a
case, it doesn’t execute subsequent cases (see the example below). As soon
as a break is encountered in switch-case block, the control comes out of the
switch-case body.

• Syntax of break statement:


– “break” word followed by semi colon
48
break;
Example – Use of break in a while loop
• In the example below, we have a while loop running from o to 100 but
since we have a break statement that only occurs when the loop value
reaches 2, the loop gets terminated and the control gets passed to the
next statement in program after the loop body.

public class BreakExample1 {


public static void main(String args[]){
int num =0;
while(num<=100)
{
System.out.println("Value of variable is: "+num);
if (num==2) • Output:
{
Value of variable is: 0
break;
} Value of variable is: 1
num++; Value of variable is: 2
}
Out of while-loop
System.out.println("Out of while-loop");
}
}

49
Example – Use of break in a for loop
• The same thing you can see here. As soon as the var value hits
99, the for loop gets terminated.

public class BreakExample2 {

public static void main(String args[]){


int var;
for (var =100; var>=10; var --)
{
System.out.println("var: "+var);
if (var==99)
{
• Output:
break; var: 100
} var: 99
}
Out of for-loop
System.out.println("Out of for-loop");
}
}

50
Example – Use of break statement in
switch-case
public class BreakExample3 {
public static void main(String args[]){
int num=2;
• Output:
switch (num) Case 2
{
case 1:
System.out.println("Case 1 ");
break;
case 2:
System.out.println("Case 2 ");
break;
case 3:
System.out.println("Case 3 ");
break;
default:
System.out.println("Default ");
}
}
}

• In this example, we have break statement after each Case block, this is
because if we don’t have it then the subsequent case block would also
execute. The output of the same program without break would be Case 2
Case 3 Default. 51

You might also like