0% found this document useful (0 votes)
5 views45 pages

Session 4

The document discusses different types of decision-making statements in Java programming. It explains the if statement and its syntax and provides an example. It also briefly mentions the switch-case statement.

Uploaded by

adelanidev
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views45 pages

Session 4

The document discusses different types of decision-making statements in Java programming. It explains the if statement and its syntax and provides an example. It also briefly mentions the switch-case statement.

Uploaded by

adelanidev
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Fo

rA
pt
ec
h
C
en
tre
U
se
O
Fundamentals of Java

nl
y
y
Identify the need for decision-making statements

nl

O
 List the different types of decision-making statements

se
 Explain the if statement

U
 Explain the various forms of if statement

tre
 Explain the switch-case statement

en
 Explain the use of strings and enumeration in the
C
switch-case statement
h
ec

 Compare the if-else and switch-case statement


pt
rA
Fo

© Aptech Ltd. Decision-Making Constructs/Session 4 2


y
A Java program consists of a set of statements which are

nl

executed sequentially in the order in which they appear.

O
The change in the flow of statements is achieved by using

se

different control flow statements.

U
 Three categories of control flow statements supported by Java

tre
programming language are as follows:

en
Conditional • These types of statements are also referred
Statements C to as decision-making statements.
h
ec

Iteration • These types of statements are also referred


pt

Statements to as looping constructs.


rA

Branching • These types of statements are referred to as


Fo

Statements jump statements.

© Aptech Ltd. Decision-Making Constructs/Session 4 3


y
Enable us to change the flow of execution of a Java program.

nl

O
 Evaluates a condition and based on the result of evaluation, a
statement or a sequence of statements is executed.

se
Different types of decision-making statements supported by Java

U

are as follows:

tre
en
if Statement Switch-case
C Statement
h
ec
pt
rA
Fo

© Aptech Ltd. Decision-Making Constructs/Session 4 4


y
It is the most basic form of decision-making statement.

nl

O
 It evaluates a given condition and based on the result of
evaluation executes a certain section of code.

se
If the condition evaluates to true, then the statements present

U

within the if block gets executed.

tre
 If the condition evaluates to false, the control is transferred

en
directly to the statement outside the if block.
C
h
ec
pt
rA
Fo

© Aptech Ltd. Decision-Making Constructs/Session 4 5


y
Following figure shows the flow of execution for the if

nl

statement:

O
se
U
tre
en
C
h
ec
pt
rA
Fo

© Aptech Ltd. Decision-Making Constructs/Session 4 6


y
The syntax for using the if statement is as follows:

nl

O
Syntax

se
if (condition) {

U
// one or more statements;

tre
}

en
where,
C
condition: Is the boolean expression.
h
ec

statements: Are instructions/statements enclosed in curly


pt

braces. These statements are executed when the boolean


expression evaluates to true.
rA
Fo

© Aptech Ltd. Decision-Making Constructs/Session 4 7


y
Following code snippet demonstrates the code that performs

nl

conditional check on the value of a variable:

O
public class CheckNumberValue {

se
/**
* @param args the command line arguments

U
*/
public static void main(String[] args) {

tre
int first = 400, second = 700, result;
result = first + second;

en
// Evaluates the value of result variable
if (result > 1000) {

}
second = second + 100;
C
h
System.out.println(“The value of second is “ + second);
ec

}
}
pt
rA

 The program tests the value of the variable, result and accordingly
calculates value for the variable, second.
Fo

 If the value of result is greater than 1000, then the value of the variable
second is incremented by 100.
© Aptech Ltd. Decision-Making Constructs/Session 4 8
y
 If the evaluation of condition is false, the value of the variable second

nl
is not incremented.

O
 Finally, the value of the variable second gets printed on the console.

se
 Following figure shows the output of the code:

U
tre
en
C
h
 If there is only a single action statement within the body of the
ec

if block, then use of opening and closing curly braces is


pt

optional.
rA
Fo

© Aptech Ltd. Decision-Making Constructs/Session 4 9


y
Sometimes, it is required to define a block of statements to be

nl

executed when a condition evaluates to false.

O
This is done by using the if-else statement.

se

if-else Statement:

U

 Begins with the if block followed by the else block.

tre
 else block specifies a block of statements that are to be executed when

en
a condition evaluates to false.
The syntax for using the if-else statement is as follows:

Syntax C
h
ec

if (condition) {
pt

// one or more statements;


}
rA

else {
// one or more statements;
Fo

© Aptech Ltd. Decision-Making Constructs/Session 4 10


y
Following code snippet demonstrates the code that checks

nl

whether a number is even or odd:

O
se
public class Number_Division {

/**

U
* @param args the command line arguments
*/

tre
public static void main(String[] args) {
int number = 11, remainder;

en
// % operator to return the remainder of the division
remainder = number % 2;
if (remainder == 0) { C
h
System.out.println(“Number is even”);
ec
} else {
System.out.println(“Number is odd”);
pt

}
}
rA

In the code, the variable, number is divided by 2 to obtain the remainder


Fo

of the division.

© Aptech Ltd. Decision-Making Constructs/Session 4 11


y
 The % (modulus) operator which returns the remainder after performing

nl
the division.

O
 If the remainder is 0, the message Number is even is printed.

se
Otherwise, the message Number is odd is printed.

U
 Following figure shows the output of the code:

tre
en
C
h
ec
pt
rA
Fo

© Aptech Ltd. Decision-Making Constructs/Session 4 12


y
An if statement can also be used within another if statement

nl

forming a nested-if.

O
A nested-if statement is an if statement that is the target of

se

another if or else statement.

U
 The syntax to use the nested-if statements is as follows:

tre
Syntax

en
if(condition) {

if(condition)
C
h
true-block statement(s);
else
ec

false-block statement(s);
}
pt
rA

else {
false-block statement(s);
}
Fo

© Aptech Ltd. Decision-Making Constructs/Session 4 13


y
Following code snippet checks whether a number is divisible by 3

nl

as well as 5:

O
se
import java.util.*;
public class NumberDivisibility {
/**

U
* @param args the command line arguments
*/

tre
public static void main(String[] args) {
// Scanner class is used to accept values from the user

en
Scanner input = new Scanner(System.in);
System.out.println(“Enter a Number: “);

C
int num = input.nextInt();
h
// Checks whether a number is divisible by 3
ec

if (num % 3 == 0) {
System.out.println(“Inside Outer if Block”);
pt

// Inner if statement checks if number is divisible by 5


rA

if (num % 5 == 0) {
System.out.println(“Number is divisible by 3 and 5”);
Fo

} else {
System.out.println(“Number is divisible by 3, but not by 5”);
} // End of inner if-else statement

© Aptech Ltd. Decision-Making Constructs/Session 4 14


y
} else {

nl
System.out.println(“Number is not divisible by 3”);

O
} // End of outer if-else statement
}

se
}

U
 The code declares a variable num to store an integer value accepted from

tre
the user.
 Initially, the outer if statement is evaluated. If it evaluate to:

en
 false, then the inner if-else statement is skipped and the final else
block is executed.
C
true, then its body containing the inner if-else statement is evaluated.
h

ec

 Following figure shows the output of the code:


pt
rA
Fo

© Aptech Ltd. Decision-Making Constructs/Session 4 15


y
The important points to remember about nested-if statements

nl

are as follows:

O
se
U
An else statement should always refer to the nearest if statement.

tre
en
C
The if statement must be within the same block as the else and it
h
should not be already associated with some other else statement.
ec
pt
rA
Fo

© Aptech Ltd. Decision-Making Constructs/Session 4 16


y
The multiple if construct is known as the if-else-if ladder.

nl

O
 The conditions are evaluated sequentially starting from the top
of the ladder and moving downwards.

se
When a condition controlling the if statement is evaluated as

U

true, then the associated statements associated are executed

tre
and all other else-if statements are bypassed.

en
 If none of the condition is true, then the final else statement
C
also referred as default statement is executed.
h
ec
pt
rA
Fo

© Aptech Ltd. Decision-Making Constructs/Session 4 17


y
 The syntax for using the if-else-if statement is as follows:

nl
O
Syntax

se
if(condition) {
// one or more statements

U
}

tre
else if (condition) {

en
// one or more statements
}

else {
C
h
ec
// one or more statements
}
pt
rA
Fo

© Aptech Ltd. Decision-Making Constructs/Session 4 18


y
Following figure shows the flow of execution for the if-else-

nl

if ladder:

O
se
U
tre
en
C
h
ec
pt
rA
Fo

© Aptech Ltd. Decision-Making Constructs/Session 4 19


y
Following code snippet checks the total marks and prints the

nl

appropriate grade:

O
public class CheckMarks {

se
/**
* @param args the command line arguments

U
*/
public static void main(String[] args) {

tre
int totalMarks = 59;
/* Tests the value of totalMarks and accordingly transfers

en
* control to the else if statement
*/
if (totalMarks >= 90) {
C
System.out.println(“Grade = A+”);
} else if (totalMarks >= 60) {
h
System.out.println(“Grade = A”);
ec

} else if (totalMarks >= 40) {


System.out.println(“Grade = B”);
pt

} else if (totalMarks >= 30) {


rA

System.out.println(“Grade = C”);
} else {
System.out.println(“Fail”);
Fo

}
}
}
© Aptech Ltd. Decision-Making Constructs/Session 4 20
y
If the code satisfies a given condition, then:

nl

The statements within that else if condition are executed.

O

 After execution of the statements, the control breaks.

se
 Remaining if conditions are bypassed for evaluation.

U
 If none of the condition is satisfied, then:
The final else statement, also known as the default else statement is

tre

executed.

en
 Following figure shows the output of the code:

C
h
ec
pt
rA
Fo

© Aptech Ltd. Decision-Making Constructs/Session 4 21


y
 Alternative for too many if statements representing multiple selection

nl
constructs.

O
 Contains a variable as an expression whose value is compared against

se
different values.

U
 Results in better performance.
Can have a number of possible execution paths depending on the value of

tre

expression provided with the switch statement.

en
 Can evaluate different primitive data types, such as byte, short, int, and
char.
C
h
ec
pt
rA
Fo

© Aptech Ltd. Decision-Making Constructs/Session 4 22


y
nl
O
Enhancements to switch-case statement in Java SE 7

se
U
tre
• Supports the use of strings in the switch-case statement.

en
• String variable can be passed as an expression for the switch
statement.
C
• Supports use of objects from classes present in the Java API.
h
• The classes whose objects can be used are Character, Byte,
ec

Short, and Integer.


pt

• Supports the use of enumerated types as expression.


rA
Fo

© Aptech Ltd. Decision-Making Constructs/Session 4 23


y
 The syntax for using the switch-case statement is as follows:

nl
Syntax

O
se
switch (<expression>) {
case value1:
// statement sequence

U
break;
case value2:

tre
// statement sequence
break;

en
. . .
. . .
. . .
case valueN: C
h
// statement sequence
ec
break;
default:
pt

// default statement sequence


}
rA

where,
switch: The switch keyword is followed by an expression enclosed in
Fo

parentheses.

© Aptech Ltd. Decision-Making Constructs/Session 4 24


y
case: The case keyword is followed by a constant and a colon. Each case

nl
value is a unique literal.

O
default: If no case value matches the switch expression value, execution

se
continues at the default clause.

U
break: The break statement is used inside the switch-case statement
to terminate the execution of the statement sequence. It is optional. If there

tre
is no break statement, execution flows sequentially into the next cases.

en
C
h
ec
pt
rA
Fo

© Aptech Ltd. Decision-Making Constructs/Session 4 25


y
 Following figure shows the flow of execution for the switch-case

nl
statement:

O
se
U
tre
en
C
h
ec
pt
rA
Fo

© Aptech Ltd. Decision-Making Constructs/Session 4 26


y
nl
The value of the expression specified with the switch

O
statement is compared with each case constant value.

se
If any case value matches, the corresponding

U
statements in that case are executed.

tre
en
When the break statement is encountered, it
terminates the switch-case block and control
C
switches to the statements following the block.
h
ec

The break statement must be provided as without it,


even after the matching case is executed; all other cases
pt

following the matching case are also executed.


rA
Fo

If there is no matching case, then the default case is


executed.

© Aptech Ltd. Decision-Making Constructs/Session 4 27


y
Following code snippet demonstrates the use of the switch-

nl

case statement:

O
public class TestNumericOperation {

se
/**

U
* @param args the command line arguments
*/

tre
public static void main(String[] args) {

en
// Declares and initializes the variable
int choice = 3;

C
// switch expression value is matched with each case
switch (choice) {
h
case 1:
ec

System.out.println(“Addition”);
break;
pt

case 2:
System.out.println(“Subtraction”);
rA

break;
case 3:
Fo

System.out.println(“Multiplication”);
break;

© Aptech Ltd. Decision-Making Constructs/Session 4 28


y
case 4:

nl
System.out.println(“Division”);

O
break;
default:

se
System.out.println(“Invalid Choice”);
} // End of switch-case statement
}

U
}

tre
 Value of the expression, choice is compared with the literal value in

en
each of the case statement.
Here, case 3 is executed, as its value is matching with the expression.
C

 The control moves out of the switch-case, due to the presence of the
h
break statement.
ec

 Following figure shows the output of the code:


pt
rA
Fo

© Aptech Ltd. Decision-Making Constructs/Session 4 29


y
 Sometimes, it is required to have multiple case statements to be executed

nl
without a break statement.

O
 Following code snippet demonstrates the use of multiple case statements

se
with no break statement:

U
public class NumberOfDays {
/**

tre
* @param args the command line arguments
*/

en
public static void main(String[] args) {

int month = 5;
int year = 2001;
int numDays = 0; C
h
ec

// Cases are executed until a break statement is encountered


switch (month) {
pt

case 1:
case 3:
rA

case 5:
case 7:
Fo

© Aptech Ltd. Decision-Making Constructs/Session 4 30


y
case 8:

nl
case 10:

O
case 12:
numDays = 31;

se
break;
case 4:
case 6:

U
case 9:
case 11:

tre
numDays = 30;
break;

en
case 2:
if (year % 4 == 0) {

C
numDays = 29;
} else {
h
numDays = 28;
ec
}
break;
pt

default:
System.out.println(“Invalid Month”);
rA

} // End of switch-case statement


System.out.println(“Month: “ + month);
System.out.println(“Number of Days: “ + numDays);
Fo

}
}

© Aptech Ltd. Decision-Making Constructs/Session 4 31


y
 The value of expression, month is compared through each case, till a

nl
break statement or end of the switch-case block is encountered.

O
 Following figure shows the output of the code:

se
U
tre
en
C
h
ec
pt
rA
Fo

© Aptech Ltd. Decision-Making Constructs/Session 4 32


y
 Java SE 7 supports the use of strings in the switch-case statement.

nl
A String is not a primitive data type, but an object in Java.

O

 To use strings for comparison, a String object is passed as an expression in

se
the switch-case statement.

U
 Following code snippet demonstrates the use of strings in the switch-case
statement:

tre
public class DayofWeek {

en
/**

C
* @param args the command line arguments
*/
h
public static void main(String[] args) {
ec
String day = “Monday”;
pt

// switch statement contains an expression of type String


rA

switch (day) {
case “Sunday”:
System.out.println(“First day of the Week”);
Fo

break;

© Aptech Ltd. Decision-Making Constructs/Session 4 33


y
case “Monday”:

nl
System.out.println(“Second Day of the Week”);
break;

O
case “Tuesday”:
System.out.println(“Third Day of the Week”);

se
break;
case “Wednesday”:

U
System.out.println(“Fourth Day of the Week”);
break;

tre
case “Thursday”:
System.out.println(“Fifth Day of the Week”);

en
break;
case “Friday”:

C
System.out.println(“Sixth Day of the Week”);
break;
h
case “Saturday”:
System.out.println(“Seventh Day of the Week”);
ec

break;
default:
pt

System.out.println(“Invalid Day”);
rA

}// End of switch-case statement


}
}
Fo

© Aptech Ltd. Decision-Making Constructs/Session 4 34


y
 The statement String day=”Monday” creates an object named day

nl
of type String and initializes it.

O
 The object is passed as an expression to the switch statement.

se
 The value of this expression, that is “Monday”, is compared with the
value of each case statement.

U
If no matching statement is found, then the statement associated with the

tre

default clause is executed.

en
 Following figure shows the output of the code:
C
h
ec
pt
rA
Fo

© Aptech Ltd. Decision-Making Constructs/Session 4 35


y
Following points are to be considered while using strings with the

nl

switch-case statement:

O
se
Null Values

U
• A runtime exception is generated when a String variable is

tre
assigned a null value and is passed as an expression to the
switch statement.

en
Case-sensitive values C
h
• The value of String variable that is matched with the case
ec

literals is case sensitive.


pt

• Example: a String value “Monday” when matched with the


rA

case labeled “MONDAY”:, then it will not be treated as a matched


value.
Fo

© Aptech Ltd. Decision-Making Constructs/Session 4 36


y
 The switch-case statement supports the use of an enumeration (enum)

nl
value in the expression.

O
 The constraint with an enum expression is that:

se
 All case constants must belong to the same enum variable used with the switch

U
statement.
Following code snippet demonstrates the use of enumerations in the

tre

switch-case statement:

en
public class TestSwitchEnumeration {

/**
C
* An enumeration of Cards Suite
h
*/
ec

enum Cards {
pt

Spade, Heart, Diamond, Club


}
rA

/**
* @param args the command line arguments
*/
Fo

public static void main(String[] args) {


Cards card = Cards.Diamond;

© Aptech Ltd. Decision-Making Constructs/Session 4 37


y
// enum variable is used to control a switch statement

nl
switch (card) {
case Spade:

O
System.out.println(“SPADE”);
break;

se
case Heart:
System.out.println(“HEART”);

U
break;
case Diamond:

tre
System.out.println(“DIAMOND”);
break;

en
case Club:
System.out.println(“CLUB”);
break;

} C
} // End of switch-case statement
h
}
ec
pt

 The enum, card is passed as an expression to the switch statement.


rA

 Each case statement has an enumeration constant associated with it and


does not require it to be qualified by the enumeration name.
Fo

© Aptech Ltd. Decision-Making Constructs/Session 4 38


y
Following figure shows the output of the code:

nl

O
se
U
tre
en
C
h
ec
pt
rA
Fo

© Aptech Ltd. Decision-Making Constructs/Session 4 39


y
 A switch-case statement can be used as a part of another switch-

nl
case statement . This is referred to as nested switch-case statements.

O
 Following code snippet demonstrates the use of nested switch-case

se
statements:

U
public class Greeting {
/**

tre
* @param args the command line arguments
*/

en
public static void main(String[] args) {
// String declaration
String day = “Monday”;
String hour = “am”;
C
h
// Outer switch statement
ec

switch (day) {
case “Sunday”:
pt

System.out.println(“Sunday is a Holiday...”);
// Inner switch statement
rA

switch (hour) {
Fo

© Aptech Ltd. Decision-Making Constructs/Session 4 40


y
case “am”:

nl
System.out.println(“Good Morning”);

O
break;
case “pm”:

se
System.out.println(“Good Evening”);
break;
} // End of inner switch-case statement

U
break; // Terminates the outer case statement

tre
case “Monday”:
System.out.println(“Monday is a Working Day...”);

en
switch (hour) {
case “am”:

C System.out.println(“Good Morning”);
break;
h
case “pm”:
ec
System.out.println(“Good Evening”);
break;
pt

} // End of inner switch-case statement


break;
rA

default:
System.out.println(“Invalid Day”);
} // End of the outer switch-case statement
Fo

}
}

© Aptech Ltd. Decision-Making Constructs/Session 4 41


y
 The variable, day is used as an expression with the outer switch

nl
statement.

O
 If the value of day variable matches with “Sunday” or “Monday”, then

se
the inner switch-case statement is executed.
The inner switch statement compares the value of hour variable with

U

case constants “am” or “pm”.

tre
 Following figure shows the output of the code:

en
C
h
ec
pt
rA
Fo

© Aptech Ltd. Decision-Making Constructs/Session 4 42


y
The three important features of switch-case statements are

nl

as follows:

O
se
The switch-case statement differs from the if statement, as it can

U
only test for equality.

tre
en
No two case constants in the same switch statement can have identical
C
values, except the nested switch-case statements.
h
ec
pt

A switch statement is more efficient and executes faster than a set of


rA

nested-if statements.
Fo

© Aptech Ltd. Decision-Making Constructs/Session 4 43


y
 Following table lists the differences between if and switch-case

nl
statement:

O
se
if switch-case

U
Each if statement has its own Each case refers back to the original value

tre
logical expression to be evaluated of the expression in the switch statement
as true or false

en
The variables in the expression The expression must evaluate to a byte,

C
may evaluate to a value of any type short, char, int, or String
Only one of the blocks of code is If the break statement is omitted, the
h
ec
executed execution will continue into the next block
pt
rA
Fo

© Aptech Ltd. Decision-Making Constructs/Session 4 44


y
 A Java program is a set of statements, which are executed sequentially in the

nl
order in which they appear.

O
 The three categories of control flow statements supported by Java programming

se
language include: conditional, iteration, and branching statements.
The if statement is the most basic decision-making statement that evaluates a

U

given condition and based on result of evaluation executes a certain section of

tre
code.
The if-else statement defines a block of statements to be executed when a

en

condition is evaluated to false.



C
The multiple if construct is known as the if-else-if ladder with conditions evaluated
sequentially from the top of the ladder.
h
ec

 The switch-case statement can be used as an alternative approach for multiple


selections. It is used when a variable needs to be compared against different
pt

values. Java SE 7 supports strings and enumerations in the switch-case statement.


rA

 A switch statement can also be used as a part of another switch statement. This is
known as nested switch-case statements.
Fo

© Aptech Ltd. Decision-Making Constructs/Session 4 45

You might also like