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 require a
; at the end.
Basic Structure of a Switch Expression
<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 ;
};
Your Turn
Let's try it in the Java Playground.
- A student's grade is being stored in
int grade, but we want to present the String representation of the student's grade: Freshman for 9; Sophomore for 10; Junior for 11, and Senior for 12. For all other values, the grade level should be Not in High School.
- The solution is started below, predict the output of the code.
- Run the code and determine if your prediction is correct.
- Add to the code below to address each case and the default case.
- Run the code with
grade having the values: 9, 10, 11, 12, and 13. Evaluate whether it will output the correct value.
Resources
Calculator - Using Conditionals and Lambda Mini-Lab
Next Learn Tutorial