Switch Expression
Part of the Logic & Flow section of Coddy's Java journey — lesson 36 of 59.
The switch expression is a feature that allows you to write more concise switch statements and return values directly. Let's see how it works.
Create a basic switch expression that returns a value:
int number = 1;
String message = switch(number) {
case 1 -> "One";
case 2 -> "Two";
default -> "Other";
};After executing the above code, the message variable contains:
"One"
You can also handle multiple cases together:
int day = 2;
String type = switch(day) {
case 1, 2, 3, 4, 5 -> "Weekday";
case 6, 7 -> "Weekend";
default -> "Invalid day";
};After executing the above code, the type variable contains:
"Weekday"
Challenge
EasyCreate a method named getDayType that takes two arguments:
- An integer (
day) representing a day of the week (1-7) - A boolean (
abbreviated) that determines the return format
The method should use a switch expression to return the day type:
- For days 1-5 (Monday to Friday): return "WORKDAY" if not abbreviated, or "WKD" if abbreviated
- For days 6-7 (Saturday and Sunday): return "WEEKEND" if not abbreviated, or "WKND" if abbreviated
- For any other number: return "INVALID" if not abbreviated, or "INV" if abbreviated
Cheat sheet
Switch expressions allow you to write concise switch statements that return values directly using the arrow syntax (->):
int number = 1;
String message = switch(number) {
case 1 -> "One";
case 2 -> "Two";
default -> "Other";
};You can handle multiple cases together by separating them with commas:
int day = 2;
String type = switch(day) {
case 1, 2, 3, 4, 5 -> "Weekday";
case 6, 7 -> "Weekend";
default -> "Invalid day";
};Try it yourself
import java.util.Scanner;
public class Main {
public static String getDayType(int day, boolean abbreviated) {
// Write your code here
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int day = Integer.parseInt(scanner.nextLine());
boolean abbreviated = Boolean.parseBoolean(scanner.nextLine());
System.out.println(getDayType(day, abbreviated));
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays2HashMap Part 1
What is a HashMap?Declare a HashMapAccessing ValuesCheck If Key ExistsModifying DictionariesRecap - HashMap3HashMap Part 2
HashMap MethodsIterate with keySet()Iterate with entrySet()Nested HashMapRecap - Manage WarehouseRecap - HashMap Operations6Advanced Control Flow
Label StatementsSwitch ExpressionPattern MatchingGuard ClausesRecap - Control Flow