part15
part15
The Java switch statement executes one statement from mul ple condi ons. It is like if-else-if ladder
statement. The switch statement works with byte, short, int, long, enum types, String and some
wrapper types like Byte, Short, Int, and Long. Since Java 7, we can use strings in the switch
statement.
The switch statement can be described as control flow type statement which is u lized for
manipula ng the flow of program execu on and invoking various branches of code using the value of
an expression.
In other words, the switch statement tests the equality of a variable against mul ple values.
Points to Remember
o The case value must be of switch expression type only. The case value must be literal or
constant. It doesn't allow variables.
o The case values must be unique. In case of duplicate value, it renders compile- me error.
o The Java switch expression must be of byte, short, int, long (with its Wrapper
type), enums and string.
o Each case statement can have a break statement which is op onal. When control reaches to
the break statement, it jumps the control a er the switch expression. If a break statement is
not found, it executes the next case.
In Java, switch statement mainly provides a more detailed alterna ve that avoids the usage of nested
or several if-else statements when associated with an individual variable.
The syntax of the Java switch statement contains the switch keyword which is followed by the
expression that needs to be evaluated using parentheses. The men oned expression must definitely
evaluate to a definite data type which is primi ve such as int, char, or enum.