CodeBlanks Logo Icon CodeBlanks

switch with enum

Learn to use enums with switch.

Use enums with switch

switch is ideal for branching on an enum constant. Each case writes the constant name directly; no Day. prefix is added.

Day d = Day.FRIDAY;
switch (d) {
  case MONDAY: System.out.println("Hafta başı"); break;
  case FRIDAY: System.out.println("Hafta sonu yakın"); break;
}

The constant name appears bare after case; writing case Day.MONDAY: is a compile error. Without break, branches fall through. The default branch catches all remaining constants.

The default branch

The default branch runs when no case matches. If the switch covers all constants, default is unnecessary; but it is a safety net when new constants are added.

switch (d) {
  case SATURDAY:
  case SUNDAY: System.out.println("Hafta sonu"); break;
  default: System.out.println("Hafta içi");
}

To bind multiple constants to the same branch, write case labels back to back. default is placed last but its position is flexible. When a new constant is added, the compiler can warn if the switch is no longer exhaustive.

Practice Print a message for a day

Define the Day enum (at least MONDAY and FRIDAY). Build a switch for Day.FRIDAY; in the case FRIDAY branch print Hafta sonu yakın. Start with Day d = Day.FRIDAY;.

Starter code

Main.java
public class Main {
  public static void main(String[] args) {
    // Define the Day enum, assign FRIDAY to d, print a message with switch
  }
}

// Define the Day enum here

Sample solution

Main.java
enum Day { MONDAY, FRIDAY }
// inside main:
Day d = Day.FRIDAY;
switch (d) {
  case FRIDAY: System.out.println("Hafta sonu yakın"); break;
}

Expected output

Hafta sonu yakın

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What do you write after case when using switch with an enum?

  • "MONDAY"
  • MONDAY Correct answer
  • Day.MONDAY
  • Day

Explanation: the constant name is written bare after case; no Day. prefix.

2 Complete the case branch

Question
switch (d) {
  case MONDAY: System.out.println("Hafta başı"); ____
  case FRIDAY: System.out.println("Hafta sonu yakın"); break;
}
Answer
switch (d) {
  case MONDAY: System.out.println("Hafta başı"); break
  case FRIDAY: System.out.println("Hafta sonu yakın"); break;
}

Explanation: break exits the branch; without it, branches fall through.

3 Match each constant to its output

Term Meaning
MONDAY Start of week
FRIDAY Weekend near
SUNDAY Weekend
WEDNESDAY Middle day

All lessons in Beginner