2. Multiple Selection (nested if)
Syntax:
if (expression1)
statement1
else
if (expression2)
statement2
else
statement3
3. Java code (multiple
selection)
if (a>=1)
{
System.out.println ("The number you enter is :" + a);
System.out.println ("You enter the positive number");
}
else if (a<0)
{
System.out.println ("The number you enter is :" + a);
System.out.println ("You enter the negative number");
}
else
{
System.out.println ("The number you enter is :" + a);
System.out.println ("You enter the zero number");
}
4. Output
Enter the number : 15
The number you enter is :15
You enter the positive number
Enter the number : -15
The number you enter is :-15
You enter the negative number
Enter the number : 0
The number you enter is :0
You enter the zero number
5. Multiple Selections
Example
The grading scheme for a course is given as
below:
Mark Grade
90 - 100 A
80 – 89 B
70 – 79 C
60 – 69 D
0 - 59 F
Read a mark & determine the grade.
6. Multiple Selections
if (mark >= 90)
grade = ‘A’;
else if (mark >= 80)
grade = ‘B’;
else if (mark >= 70)
grade = ‘C’;
else if (mark >= 60)
grade = ‘D’;
else
grade = ‘F’;
7. Equivalent code with series of if
statements
if ((mark >= 90) && (mark <=100))
grade = ‘A’;
if ((mark >= 80) && (mark >= 89))
grade = ‘B’;
if ((mark >= 70) && (mark >= 79))
grade = ‘C’;
if ((mark >= 60) && (mark >= 69))
grade = ‘D’;
if ((mark >= 0) && (mark >= 59))
grade = ‘F’;
8. switch Structures (multiple
selection)
Expression is
also known as
selector.
Value can only
be integral.
switch (expression)
{
case value1: statements1
break;
case value2: statements2
break;
...
case valuen: statementsn
break;
default: statements
}
If expression
matches value2,
control jumps
to here
10. The switch Statement
Often a break statement is used as the last
statement in each case's statement list
A break statement causes control to transfer to
the end of the switch statement
If a break statement is not used, the flow of
control will continue into the next case
11. Control flow of switch statement
with and without the break
statements
12. Switch/Break Examples
int m = 2;
switch (m)
{
case 1 :
System.out.println(“m=1”);
break;
case 2 :
System.out.println(“m=2”);
break;
case 3 :
System.out.println(“m=3”);
break;
default:
System.out.println(“default”);}
Output: m=2
char ch = ‘b’;
switch (ch)
{
case ‘a’ :
System.out.println(“ch=a”);
case ‘b’ :
System.out.println(“ch=b”);
case ‘c’ :
System.out.println(“ch=c”);
default:
System.out.println(“default”);
}
Output: ch=b
ch=c
default