⇒ Rewrite the following if statement using switch statement :-
if(choice==1)
System.out.println(“Blue”);
else if(choice==2||choice==3)
System.out.println(“Green”);
else if(choice==4)
System.out.println(“Red”);
else
System.out.println(“Invalid choice”);
Answers
Required snippet:-
switch(choice)
{
case 1:
System. out.println("Blue");
break;
case 2:
System. out.println("Green");
break;
case 3:
System. out.println("Green");
break;
case 4:
System. out.println("Red");
break;
default:
System. out.println("Invalid choice");
}
Input:
3
Output:
Green
Must know:
Syntax of switch case:
switch (control variable)
{
case 1:
Block 1
break;
case 2:
Block 2
break;
case 3:
Block 3
break;
default:
Block 4
}
Syntax of if else if:
//{} can be omitted if there is only one Statement under condition
if(condition 1)
{
statement 1
}
else if(condition 2)
{
statement 2
}
else
{
statement 3
}
Additional information:
What will happen if break statement is not used ?
If break statement is not used then flow of control will go out side the loop which will result in fall through due to which program will not able to execute.
Explanation:
int val = 2;
switch (val)
{
case 1: System.out.println("Case 1");
break;
case 2: System.out.println("Case 2");
break;
default: System.out.println("No match found");
break;
}