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 break keyword to avoid "falling" to the next case. Forgetting to include a break is a common mistake that can lead to unexpected behavior.
  • Default: Although not required, it is good practice to include a default clause 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 switch expression 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.

Now answer the exercise about the content:

_Which of the following statements about the `switch` declaration in Java is correct?

You are right! Congratulations, now go to the next page

You missed! Try again.

Article image Arrays and the Arrays class

Next page of the Free Ebook:

55Arrays and the Arrays class

5 minutes

Obtenez votre certificat pour ce cours gratuitement ! en téléchargeant lapplication Cursa et en lisant lebook qui sy trouve. Disponible sur Google Play ou App Store !

Get it on Google Play Get it on App Store

+ 6.5 million
students

Free and Valid
Certificate with QR Code

48 thousand free
exercises

4.8/5 rating in
app stores

Free courses in
video, audio and text