The switch statement in Java is a control flow statement that allows the execution of one block of code among multiple alternatives. It provides a more readable and efficient way of writing a series of if-else statements when comparing the same expression against different values.
Usage
The switch statement evaluates an expression, matches the expression's value against a series of case labels, and executes the block of code associated with the matching case. If no case matches, the default block is executed, if it is present.
Syntax
switch(expression){casevalue1:// code blockbreak;casevalue2:// code blockbreak;// more cases...default:// default code block}Altyapı:
expression: A variable or expression that is evaluated once.
value1, value2, ...: Constant expressions that the expression is compared against.
break: Terminates the switch block. Without it, execution falls through to subsequent cases.
default: Optional block executed if no case matches.
Examples
Example 1: Basic switch Statement
publicclassSwitchExample{publicstaticvoidmain(String[] args){
int number =2;switch(number){case1:
System.out.println("One");break;case2:
System.out.println("Two");break;case3:
System.out.println("Three");break;default:
System.out.println("Not in range");}}}Altyapı:
In this example, the switch statement evaluates the variable number. Since number equals 2, the output will be "Two". The break statement prevents fall-through to subsequent cases.
Example 2: switch with 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;default:
System.out.println("Unknown fruit");}}}Altyapı:
This example demonstrates the use of a switch statement with a String. The switch checks the value of fruit, and since it is "Apple", the output will be "Fruit is Apple".
Example 3: switch without break
publicclassSwitchFallThroughExample{publicstaticvoidmain(String[] args){
int day =3;switch(day){case1:case2:case3:
System.out.println("Weekday");break;case4:case5:
System.out.println("Weekend");break;default:
System.out.println("Invalid day");}}}Altyapı:
In this example, multiple case labels are used to execute the same block of code. The output will be "Weekday" because day is 3, and the break statement prevents execution from falling through to the "Weekend" cases.
Tips and Best Practices
Use break Statements: Always include break statements unless intentional fall-through is desired. This prevents unintended execution of subsequent cases.
Default Case: Include a default case to handle unexpected values and improve code robustness.
Expression Types: The switch expression can be of type byte, short, int, char, String, or an enum.
Avoid Complex Logic: Use switch for simple scenarios with discrete values. For complex conditions, consider using if-else statements.
Java 12+ Enhancements: In Java 12 and later, switch expressions allow returning values and using the yield keyword for more concise code.
The
switchstatement in Java is a control flow statement that allows the execution of one block of code among multiple alternatives. It provides a more readable and efficient way of writing a series ofif-elsestatements when comparing the same expression against different values.Usage
The
switchstatement evaluates an expression, matches the expression's value against a series ofcaselabels, and executes the block of code associated with the matchingcase. If nocasematches, thedefaultblock is executed, if it is present.Syntax
expressionis compared against.switchblock. Without it, execution falls through to subsequent cases.casematches.Examples
Example 1: Basic
switchStatementIn this example, the
switchstatement evaluates the variablenumber. Sincenumberequals 2, the output will be "Two". Thebreakstatement prevents fall-through to subsequent cases.Example 2:
switchwith StringsThis example demonstrates the use of a
switchstatement with aString. Theswitchchecks the value offruit, and since it is "Apple", the output will be "Fruit is Apple".Example 3:
switchwithoutbreakIn this example, multiple
caselabels are used to execute the same block of code. The output will be "Weekday" becausedayis 3, and thebreakstatement prevents execution from falling through to the "Weekend" cases.Tips and Best Practices
breakStatements: Always includebreakstatements unless intentional fall-through is desired. This prevents unintended execution of subsequent cases.defaultcase to handle unexpected values and improve code robustness.switchexpression can be of typebyte,short,int,char,String, or an enum.switchfor simple scenarios with discrete values. For complex conditions, consider usingif-elsestatements.yieldkeyword for more concise code.