Week 47 — What is a switch expression and how is it different from switch statements?
Question of the Week #47
What is a switch expression and how is it different from switch statements?
4 Replies
The
switch
statement allows to execute different code depending on the value of an expression:
This code prints different text depending on what is stored inside value
without printing anything for E
.
If we instead wanted to store text in a variable, we would need to assign that variable in every case
:
With switch expressions, it is possible to assign give back a value in each case and then use the result of the combined
switch
expression somewhere else.
However, that requires exhaustiveness i.e. every possible case needs to be matched:
The result of the switch expression is assigned to the variable result
and the compiler checks that a value exists in every case.📖 Sample answer from dan1st
Switch expression evaluates to a value and can be used in switch statements but switch statements are the executes statements from multiple conditions.Switch statements are also called switch case.
Let's explain this with an example: Day day = Day.WEDNESDAY;
System.out.println( switch (day) { case MONDAY, FRIDAY, SUNDAY -> 6; case TUESDAY -> 7; case THURSDAY, SATURDAY -> 8; case WEDNESDAY -> 9; default -> throw new IllegalStateException("Invalid day: " + day); } ); The above code block is a switch expression that uses the new kind of case label to print the number of letters of a day of the week.
System.out.println( switch (day) { case MONDAY, FRIDAY, SUNDAY -> 6; case TUESDAY -> 7; case THURSDAY, SATURDAY -> 8; case WEDNESDAY -> 9; default -> throw new IllegalStateException("Invalid day: " + day); } ); The above code block is a switch expression that uses the new kind of case label to print the number of letters of a day of the week.
Switch statement with example:public enum Day { SUNDAY, MONDAY, TUESDAY,
WEDNESDAY, THURSDAY, FRIDAY, SATURDAY; }
// ...
int numLetters = 0;
Day day = Day.WEDNESDAY;
switch (day) {
case MONDAY:
case FRIDAY:
case SUNDAY:
numLetters = 6;
break;
case TUESDAY:
numLetters = 7;
break;
case THURSDAY:
case SATURDAY:
numLetters = 8;
break;
case WEDNESDAY:
numLetters = 9;
break;
default:
throw new IllegalStateException("Invalid day: " + day);
}
System.out.println(numLetters);
Submission from dasa_51082