Free Ebook cover Learn to program in complete Java, from programming logic to advanced

Learn to program in complete Java, from programming logic to advanced

3.5

(4)

238 pages

Flow control (if, else, switch, loops): Declaration of multiple cases in switch

Capítulo 54

Estimated reading time: 5 minutes

Audio Icon

Listen in audio

0:00 / 0:00

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:

Continue in our app.

You can listen to the audiobook with the screen off, receive a free certificate for this course, and also have access to 5,000 other free online courses.

Or continue reading below...
Download App

Download the app


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.

The switch statement allows multiple cases to execute the same block of code by lining them up without a code block or a break statement in between. This approach is commonly used when multiple case values should result in the execution of the same code.

Next chapter

Arrays and the Arrays class

Arrow Right Icon
Download the app to earn free Certification and listen to the courses in the background, even with the screen off.