Switch Expression in Java with Example

Switch Expression
DefinitionSyntaxExampleOutputFeature Timeline
What is Switch Expression in Java ?

Switch Expression is a new feature introduced in Java 12, which allows developers to use switch statements as expressions instead of just statements.

This means that a switch expression returns a value, which can be assigned to a variable or used in an expression.

Syntax:

The syntax of the switch expression in Java is:

Here, 'expression' is the value that is being compared to the case values.

Each case value can be followed by an arrow case label '->' and an expression that will be executed if the case value matches the 'expression'.

If multiple case values have the same expression, they can be combined using a comma ','.

The 'default' keyword is used if none of the case values match the expression.

Example:

Here is an example of a switch expression in Java using arrow case labels :

In this example, we have a variable 'dayOfWeek' that represents the day of the week.

We use a switch expression to determine whether it is a weekday or a weekend.

  • If the value of 'dayOfWeek' is between 1 and 5, it will match the first case and return the string "Weekday".
  • If the value is 6 or 7, it will match the second case and return the string "Weekend".
  • If the value is not valid, it will throw an exception with an error message.
Output:

The output of this program will be:

Weekday

Because the value of 'dayOfWeek' is 2, which matches the first case of the switch expression.

Feature Timeline:
  • First introduced in Java 12 as a preview feature.
  • In Java 13, the 'break' keyword was replaced by 'yield'.
  • Released as a final feature in Java 14 without any further changes.
Share This Post On: