How To Use Switch Statement and Expressions In Java

By bhagwatchouhan
How To Use Switch Statement and Expressions In Java

We can use the Switch Case statements to conditionally execute the code based on the result of the Switch Statement expression and the matching case to execute only a set of statements within the matched case. Almost all the programming languages support the Switch Case statement and Java is no exception to it. There are few fallbacks in using the Switch Case Statement in the traditional way and Java 13 is introducing enhancements to its existing behavior of it. Apart from the traditional way of using the Switch Case Statement, Java 12 also added options to use Switch Case via expressions which are going to make it easy to use it inline. Java 13 has further enhanced it by introducing the keyword yield to output case results.

The remaining sections of this tutorial explain using Switch Case in both the traditional way and the new approach via expressions.

 

Traditional Switch Case Statement

The Switch Case Statement can accept the expression as byte, short, char, and int primitive data types prior to JDK 7. With the release of JDK 7, the expression works with Enums, String, and Wrapper classes. The traditional way of using Switch Statement supports fallthrough which can introduce bugs in case the programmer forgets to add an appropriate break statement.

The syntax of the Switch Case Statement is as mentioned below.

// Switch Statement 
switch( Conditional Expression ) {
	// Case Statement having value type same as that of the Expression
	case option1:
		// Case Statements
	break;
	case option2:
		// Case Statements
break; default:
// Default Statements } // OR - More readable with clear separation of case statements switch( Expression ) {
// Case Statement having value type same as that of the Expression
case option1: {
// Case Statements
break;
} case option2: {
// Case Statements
break;
}
default: {
// Default Statements } }

Below listed are the rules to be followed while using Switch Statement.

  1. Duplicate case values are not allowed i.e. two cases cannot have the same value.
  2. The data type of switch expression and case value must be the same.
  3. Variables are not allowed to be used as casevalue. Only final variables can be used as case value.
  4. The break statement within the case is optional i.e. it is not mandatory to provide a break statement for a case.
  5. The default statement is optional, and there is no need to use a statement within it. If the default statement is not the last one, it must have the break statement to terminate the execution of the Switch Statement.

A complete working example showing the implementation of the Switch Statement is mentioned below.

package com.example;
public class HelloJava {
public static void main( String[] args ) {
int num = 0;
// Switch Statement
switch( num ) {
// Case Statement having value type same as that of the Expression
case 0:
System.out.println( "I am at 0" );
break;
case 1:
System.out.println( "I am at 1" );
break;
default:
System.out.println( "I am at default" ); } num = 1;
// OR - More readable with clear separation of case statements switch( num ) {
// Case Statement having value type same as that of the Expression case 0: {
System.out.println( "I am at 0" );
break; } case 1: {
System.out.println( "I am at 1" );
break; } default: {
System.out.println( "I am at default" ); } } } }

The output of the above-mentioned example is as shown below.

I am at 0
I am at 1

Suppose the programmer forgot to add the break statement in case having value 1 as shown below.

// OR - More readable with clear separation of case statements
// Switch Statement with invalid fall through
switch( num ) {
    // Case Statement having value type same as that of the Expression
    case 0: {
        System.out.println( "I am at 0" );
break; } case 1: {
System.out.println( "I am at 1" );
// Missed break - introduces bug } default: {
System.out.println( "I am at default" ); } }

The output of the above-mentioned example is as shown below.

I am at 0
I am at 1
I am at default

We can see that the default statements also get executed in case we accidentally forget to add the break statement within the case having value 1. This is called as fall through i.e. if we do not add a break statement within the matching case, the next case statements get executed and so on till the execution reaches the end of Switch Statement or encounters break statement.

In certain situations, omitting the break statement within the cases is desired behavior if the multiple cases expect to execute the same set of statements as shown below.

// Switch Statement with valid fall through
switch( num ) {
	// Case Statement having value type same as that of the Expression
	case 0:
	case 1: {
System.out.println( "I am at 0 or 1" );
break; } case 2: {
System.out.println( "I am at 2" );
break; } default: {
System.out.println( "I am at default" ); } }

This is how we can use the Switch Statement traditionally with fall through. This section also explains the situations having valid and invalid fall through.

 

Newer Switch Case Statement

JDK 13 added an option to specify multiple values for the case statement as shown below. Now we can specify multiple values separated by a comma for a case statement.

// Switch Statement with valid fall through
switch( num ) {
	// Case Statement having multiple values separated by comma
	case 0, 1: {
		System.out.println( "I am at 0 or 1" );
		break;
	}
	case 2: {
		System.out.println( "I am at 2" );
break; } default: {
System.out.println( "I am at default" ); } }

 

Switch Case Expressions

This section explains using Switch Case Expressions introduced in Java 12 and enhanced in Java 13. This feature is still a preview language feature i.e. it can change in the next versions of JDK. It can only be used by unlocking the preview features using the command line option --enable-preview. The Switch Expression can be used in two ways as shown below. Also, it does not allow fall through as we saw in previous sections.

// Switch Expression
String optionVal = switch( option ) {
    case 1:
        yield "Option 1";
    case 2:
        yield "Option 2";
    default:
        throw new IllegalArgumentException( "Invalid option: " + option );
};
// OR lambda-style syntax String optionVal = switch( option ) { case 1 -> "Option 1"; case 2 -> "Option 2"; case 3, 4 -> "It sounds great !!"; default -> { throw new IllegalArgumentException( "Invalid option: " + option ); } };

We can also use statement blocks for the case statements for better readability of the code as shown below.

// Switch Expression with Case Blocks
String optionVal = switch( option ) {
	case 1 -> {
		yield "Option 1";
	}
	case 2 -> {
yield "Option 2"; } case 3, 4 -> {
yield "It sounds great !!"; } default -> {
throw new IllegalArgumentException( "Invalid option: " + option ); } };

With the introduction of Switch Expressions, we can have an inline switch case to conditionally return value based on the switch expression.

 

Summary

This tutorial explained the usage of the switch statements in both the traditional way and using Switch Expressions introduced in Java 13.

Share this blog:

Profile picture for user bhagwatchouhan
bhagwatchouhan