The switch keyword in Java is used to execute one block of code among many alternatives. It is a control statement that allows the variable to be tested for equality against a list of values, each with its own block of code.
Usage
The switch statement provides a cleaner and more readable way to handle multiple conditional branches compared to using multiple if-else statements.
Syntax
switch(expression){casevalue1:// code blockbreak;casevalue2:// code blockbreak;// more cases...default:// default code block}Drivs av
expression: The variable or expression whose value is compared against the case values.
case value: A constant value that the expression is compared to. If they match, the corresponding code block is executed.
break: Terminates the switch statement, preventing fall-through.
default: Executes if no case value matches the expression.
Examples
Example 1: Basic Usage
publicclassSwitchExample{publicstaticvoidmain(String[] args){
int day =3;switch(day){case1:
System.out.println("Monday");break;case2:
System.out.println("Tuesday");break;case3:
System.out.println("Wednesday");break;case4:
System.out.println("Thursday");break;case5:
System.out.println("Friday");break;case6:
System.out.println("Saturday");break;case7:
System.out.println("Sunday");break;default:
System.out.println("Invalid day");}}}Drivs av
In this example, the variable day is compared against the case values. Since day is 3, the output will be "Wednesday".
Example 2: Using Strings
publicclassSwitchStringExample{publicstaticvoidmain(String[] args){
String fruit ="Apple";switch(fruit){case"Apple":
System.out.println("Fruit is Apple");break;case"Banana":
System.out.println("Fruit is Banana");break;case"Cherry":
System.out.println("Fruit is Cherry");break;default:
System.out.println("Unknown fruit");}}}Drivs av
This example demonstrates how to use a switch statement with String values. Since fruit is "Apple", the output will be "Fruit is Apple".
Example 3: Fall-Through Behavior
publicclassSwitchFallThroughExample{publicstaticvoidmain(String[] args){
int num =2;switch(num){case1:
System.out.println("One");case2:
System.out.println("Two");case3:
System.out.println("Three");break;default:
System.out.println("Default case");}}}Drivs av
In this example, the absence of break statements results in fall-through behavior. Since num is 2, the output will be:
Use break Statements: Always use break statements to prevent fall-through unless explicitly desired.
Default Case: Include a default case to handle unexpected values.
Constant Values: Ensure that case values are constants or literals.
Type Compatibility: The switch expression can be of types byte, short, char, int, String, or an enum type. Ensure the case values are compatible with the type of the expression.
Readable Code: Use switch statements to make your code more readable and maintainable compared to multiple if-else statements.
Java 12 Enhancements: As of Java 12, you can use switch expressions to return values directly from cases, simplifying the syntax and enhancing code readability.
enum Day {MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY,SUNDAY}publicclassSwitchEnumExample{publicstaticvoidmain(String[] args){
Day day = Day.WEDNESDAY;switch(day){caseMONDAY:
System.out.println("Monday");break;caseTUESDAY:
System.out.println("Tuesday");break;caseWEDNESDAY:
System.out.println("Wednesday");break;caseTHURSDAY:
System.out.println("Thursday");break;caseFRIDAY:
System.out.println("Friday");break;caseSATURDAY:
System.out.println("Saturday");break;caseSUNDAY:
System.out.println("Sunday");break;}}}Drivs av
Using enums in switch statements can enhance code readability and type safety.
The
switchkeyword in Java is used to execute one block of code among many alternatives. It is a control statement that allows the variable to be tested for equality against a list of values, each with its own block of code.Usage
The
switchstatement provides a cleaner and more readable way to handle multiple conditional branches compared to using multipleif-elsestatements.Syntax
expression: The variable or expression whose value is compared against the case values.case value: A constant value that the expression is compared to. If they match, the corresponding code block is executed.break: Terminates theswitchstatement, preventing fall-through.default: Executes if no case value matches the expression.Examples
Example 1: Basic Usage
In this example, the variable
dayis compared against the case values. Sincedayis 3, the output will be "Wednesday".Example 2: Using Strings
This example demonstrates how to use a
switchstatement withStringvalues. Sincefruitis "Apple", the output will be "Fruit is Apple".Example 3: Fall-Through Behavior
In this example, the absence of
breakstatements results in fall-through behavior. Sincenumis 2, the output will be:Tips and Best Practices
breakStatements: Always usebreakstatements to prevent fall-through unless explicitly desired.defaultcase to handle unexpected values.switchexpression can be of typesbyte,short,char,int,String, or an enum type. Ensure the case values are compatible with the type of the expression.switchstatements to make your code more readable and maintainable compared to multipleif-elsestatements.Using enums in
switchstatements can enhance code readability and type safety.