Switch Statement in Java
The switch statement in Java is a decision-making statement that allows a program to execute one block of code from multiple choices. It compares the value of an expression with different case values and executes the matching case block.
The switch statement is used as an alternative to multiple if-else-if statements. It makes programs cleaner, easier to understand, and more organized.
What is Switch Statement in Java?
A switch statement in Java is a control flow statement that selects one block of code from multiple options. The value given to the switch expression is checked against different case values.
When a matching case is found, the code inside that case is executed. If no case matches, the default block is executed.
Syntax of Switch Statement in Java
switch(expression) {
case value1:
// code to execute
break;
case value2:
// code to execute
break;
default;
// default code
}
Components of Switch Statement
switch
Defines the expression whose value is compared with different cases.
case
Represents possible values that can match with the switch expression.
break
Stops the execution of the switch block after a matching case.
default
Executes when none of the case values match.
How Switch Statement Works in Java?
- The switch expression is evaluated first.
- The value is compared with all available case values.
- The matching case block is executed.
- The break statement exits the switch statement.
- The default block executes if no case matches.
Example of Switch Statement in Java
public class Main {
public static voidmain(String[] args) {
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Invalid Day");
}
}
}
Switch Statement with String in Java
Java allows String values in switch statements. The string value is compared with different cases and the matching block is executed.
String language = "Java";
switch(language) {
case "Java" :
System.out.println("Java Programming");
break;
default:
System.out.println("Unknown Language");
}
Advantages of Switch Statement
Simple Code
Reduces the complexity of multiple if-else conditions.
Readability
Makes decision-making code easier to understand.
Multiple Choices
Handles multiple fixed options efficiently.
Switch vs If Else Statement
- If Else: Used for complex conditions and range checking.
- Switch: Used when comparing one value with multiple fixed values.