Computer Applications
Explain the switch statement with an example.
Java Conditional Stmts
50 Likes
Answer
switch statement in a program, is used for multi-way branch. It compares its expression to multiple case values for equality and executes the case whose value is equal to the expression of switch. If none of the cases match, default case is executed. If default case is absent and no case values match then none of the statements from switch are executed. The below program makes use of the switch statement to print the value of a number if the number is 0, 1 or 2:
class SwitchExample {
public static void demoSwitch(int number) {
switch (number) {
case 0:
System.out.println("Value of number is zero");
break;
case 1:
System.out.println("Value of number is one");
break;
case 2:
System.out.println("Value of number is two");
break;
default:
System.out.println("Value of number is greater than two");
break;
}
}
}
Answered By
26 Likes