Skip Top Navigation Bar

Switch Expressions - Determine a Value

Before you learn about switch expressions, you may want to review the tutorial on Switch Statements

Switch Expressions

How are switch expressions different from switch statements?

  • Switch expressions yield a value, typically assigned to a variable.
  • Switch expressions use the keyword yield and do not require a break statement as yield will return a value and the execution stops.
  • Switch expressions require a ; at the end.

Basic Structure of a Switch Expression

<type> returnVariable = switch (<variable>) { 
   case <value>: {
      yield valueAssignedtoreturnVariable; 
   }
   //additional case statements
   default: {
      yield valueAssignedtoreturnVariable; 
   }
};

Revisiting the Grade Level Example

We've embedded the expression into a statement requiring a semi-colon at the end.

Note that the keyword yield is being used to return the value for each case.

Basic Structure of a Switch Expression with Lambda

<type> returnVariable = switch (<variable>) { 
   case <value> -> //value to assign if variable == value ;
   //additional case statements
   default -> //value to assign if no case values match the value of variable ;
}; 

The above example re-written with lambda:

Resources

Calculator - Using Conditionals and Lambda Mini-Lab