Menu
Coddy logo textTech

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 icon

Challenge

Easy

Create a method named getDayType that takes two arguments:

  1. An integer (day) representing a day of the week (1-7)
  2. 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));
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow