Mastering switch statements and expressions
Complicated if
statements, with many else if
branches and an else
branch can be verbose. The switch
structure can, in many situations, be more concise and elegant. Let us start with switch
statements.
switch statements
Firstly, let us examine the syntax of the switch
statement. Figure 4.8 introduces the syntax.
Figure 4.8 – The switch statement syntax
A switch
statement evaluates an expression. As of Java 21, the expression can be an integral primitive (excluding long
) or any reference type. This means that we can switch
on primitive variables of type byte
, char
, short
, or int
and also switch
on class types, enum types, record types and array types. The case
labels can now include a null
label. Java 21 also brought in pattern matching for switch. We will present another switch
example demonstrating this feature when we have those topics covered (Chapter 9). Until then, we will focus on the more traditional...