Switch Statements
Switch statements are used when there is a requirement to check multiple conditions in a program. It is a substitute of large series of if-else-if statements. This control structure has a switch statement which stores an expression. It also has multiple cases where each case has a unique label and a block of code associated with it. If none expression matches, the default case is executed.
Break Statements
Break statement takes the flow of control out of switch statement, which stores an expression. Without this statement, execution would simply continue to the next case.
Syntax
switch(expression){
case(Label_1):
// Java Statements
break;
case(Label_2):
// Java Statements
break;
Example Program
Write a program to accept a number and print the corresponding color value. eg. 1: Red,2: Green,3: Blue
public class RGB{
public static void main(int val) {
switch(val){
case 1:
System.out.println("Color is Red");
break;
case 2:
System.out.println("Color is Green");
break;
case 3:
System.out.println("Color is Blue"):
break;
}
}
}
Nice bro, helpful
ReplyDeleteYour welcome!
Delete