Flow control in any programming language is essential for creating programs that can make decisions and execute different blocks of code based on specific conditions. Java, being a robust and widely used programming language, offers several constructs for flow control, including if, else, switch and loops like for, while and do-while. In this text, we will focus specifically on the switch statement and how you can use multiple cases to control the flow of your program.
The switch statement is a control flow structure that allows you to execute different parts of code based on the value of a variable. It is an alternative to using multiple if-else-if statements, providing cleaner and more readable code, especially when dealing with many conditions.
Basic Declaration of switch
In Java, the basic syntax of a switch statement is as follows:
switch (variable) {
case value1:
// Code block for value1
break;
case value2:
// Code block for value2
break;
// ...
default:
// Default code block
}
The variable used in the switch declaration can be of type byte, short, char, int, String, or enum. When the variable value matches one of the values specified in the cases (case), the associated code block is executed. The break keyword is used to exit the switch statement after executing the code block of a specific case. If none of the cases match, the code block under default is executed.
Multiple Case Declaration in switch
In certain situations, you may want multiple cases to execute the same block of code. This can be achieved by lining up cases without a code block or a break statement in between. Let's look at an example:
switch (weekday) {
case 1:
case 2:
case 3:
case 4:
case 5:
System.out.println("Business day");
break;
case 6:
case 7:
System.out.println("Weekend");
break;
default:
System.out.println("Invalid day");
}
In this example, if dayOfWeek is any value from 1 to 5, the program will print "Workday". If it is 6 or 7, it will print "Weekend". If it is any other value, it will print "Invalid day". By omitting the break statement between cases 1 to 5, we ensure that they all execute the same block of code.
Important Considerations
There are some important considerations when using the switch declaration in Java:
- Breaks: Always use the
breakkeyword to avoid "falling" to the next case. Forgetting to include abreakis a common mistake that can lead to unexpected behavior. - Default: Although not required, it is good practice to include a
defaultclause to handle any value that does not match any of the specified cases. - Constants: Case values must be constants or literals. Variables are not allowed.
- Data Types: The variable used in the
switchexpression must be compatible with the permitted types.
Java SE 12 and the switch
Expression
With Java SE 12 and later versions, the switch expression has been enhanced to support a more flexible and powerful syntax. This includes using yield to return values from a switch and the ability to use switch as an expression itself. Here is an example of how you can use switch in an expression:
String dayType = switch (weekday) {
case 1, 2, 3, 4, 5 -> "Working day";
case 6, 7 -> "Weekend";
default -> "Invalid day";
};
System.out.println(typeOfDay);
In this example, the expression switch is used to assign a value to the variable typeOfDay based on the value of dayOfWeek. The arrow syntax (->) eliminates the need for break and allows a direct expression of the result for each case.
Conclusion
The switch statement is a powerful tool for controlling the flow of your Java program. Using multiple cases to execute the same block of code can make your code more concise and easier to understand. With recent updates to the Java language, the expression switch has become even more flexible and expressive. By mastering the use of switch and other flow control constructs, you will be well equipped to write efficient and sophisticated Java programs.