Practical-5
Write a Java Program that shows the use of switch Statement.
Answer:
Introduction
A switch statement in Java is used to execute one statement from multiple expressions based on a condition. It replaces multiple if statements with a single statement. The syntax to use a switch statement is similar to the syntax of if-else statement. The break statement serves to terminate the code block and is required to exit the block and execute the corresponding code.
Code
public class Example {
public static void main(String[] args) {
String day = "Monday";
switch (day) {
case "Monday":
System.out.println("Weekday");
break;
case "Saturday":
case "Sunday":
System.out.println("Weekend");
break;
default:
System.out.println("Invalid Day");
}
}
}
Output
Weekday
The switch statement works like other statement blocks, but it uses a condition to determine which code block to execute. In the example above, the switch statement checks the value of day and executes the System.out.println() statement inside the corresponding case block.
The condition is evaluated against the constant values specified in the case blocks and in this example, if the value of day is “Monday”, the corresponding case block will be executed. The break statement terminates the execution of the case blocks.