Using Switch
In Java, a switch
statement is a control flow construct used for making decisions based on the value of a variable or expression.
It allows you to specify multiple possible execution paths based on the value of the expression.
The switch
statement is often used as an alternative to a series of if-else if-else
statements when you have a single variable to test against multiple values.
It's important to note that switch
cases in Java only work with certain data types like int
, char
, byte
, short
, and enum
, as well as their corresponding wrapper classes (e.g., Integer
, Character
, etc.)
Switch Syntax
Example:
Aside: Java 12 Switch Cases
Starting from Java 12, switch
expressions allow you to use a wider range of data types.
Here's a quick example using switch
expressions introduced in Java 12:
In this case, the switch
expression assigns a value to the result
variable based on the value of the fruit
variable. This feature simplifies switch
usage and allows you to assign values directly to variables.
Last updated