Switch case in java
In Java programming, a switch statement (also called a switch-case) is a control flow statement that allows you to execute one block of code out of many based on the value of an expression.
It is an alternative to using many if-else statements, and is often more readable and efficient when dealing with multiple conditions based on a single variable.
๐น Syntax of switch-case in Java:
switch (expression) {
case value1:
// Code block for value1
break;
case value2:
// Code block for value2
break;
// more cases...
default:
// Default code block (optional)
}
๐ธ How it works:
- The
expressionis evaluated once. - Its value is compared with each
case. - If a match is found, the corresponding code block runs.
- The
breakstatement exits the switch block. Withoutbreak, execution "falls through" to the next case. - The
defaultblock runs if none of the cases match. It is optional.
✅ Example:
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
}
Output:
Wednesday
๐น Supported Data Types in switch:
Java switch supports:
- Primitive types:
byte,short,char,int String(since Java 7)enumtypes- Wrapper classes (
Byte,Short,Character,Integer)
๐ธ Notes:
- From Java 14 onwards, you can also use the enhanced switch expression, which allows returning values from cases and eliminates the need for
break.
Comments
Post a Comment