Your app uses day-of-week values. Using integers (1=Monday, 2=Tuesday) is error-prone - what if someone passes 8? Enums define a fixed set of valid values. The compiler catches invalid values at compile time.

Define an enum

Create a type with fixed set of values.

example
DaysOfWeek.java
Replay: real traced execution (multi-file project)
// Basic enum definition and usage
// Concept: enum - type-safe constants

enum DayOfWeek {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

public class DaysOfWeek {
    public static void main(String[] args) {
        // Basic enum usage
        DayOfWeek today = DayOfWeek.MONDAY;
        System.out.println("Today is: " + today);

        // Compare enums with ==
        if (today == DayOfWeek.MONDAY) {
            System.out.println("Start of work week");
        }

        // Get enum name as string
        String dayName = today.name();
        System.out.println("Day name: " + dayName);

        // Get ordinal position (0-based index)
        int position = today.ordinal();
        System.out.println("Position in week: " + position);


        // Try different day
        DayOfWeek weekend = DayOfWeek.SATURDAY;
        System.out.println("\nWeekend day: " + weekend);
        System.out.println("Ordinal: " + weekend.ordinal());

    }
}
// Basic enum definition and usage
// Concept: enum - type-safe constants

enum DayOfWeek {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

public class DaysOfWeek {
    public static void main(String[] args) {
        // Basic enum usage
        DayOfWeek today = DayOfWeek.FRIDAY;
        System.out.println("Today is: " + today);

        // Compare enums with ==
        if (today == DayOfWeek.MONDAY) {
            System.out.println("Start of work week");
        }

        // Get enum name as string
        String dayName = today.name();
        System.out.println("Day name: " + dayName);

        // Get ordinal position (0-based index)
        int position = today.ordinal();
        System.out.println("Position in week: " + position);


        // Try different day
        DayOfWeek weekend = DayOfWeek.SATURDAY;
        System.out.println("\nWeekend day: " + weekend);
        System.out.println("Ordinal: " + weekend.ordinal());

    }
}
// Basic enum definition and usage
// Concept: enum - type-safe constants

enum DayOfWeek {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

public class DaysOfWeek {
    public static void main(String[] args) {
        // Basic enum usage
        DayOfWeek today = DayOfWeek.SUNDAY;
        System.out.println("Today is: " + today);

        // Compare enums with ==
        if (today == DayOfWeek.MONDAY) {
            System.out.println("Start of work week");
        }

        // Get enum name as string
        String dayName = today.name();
        System.out.println("Day name: " + dayName);

        // Get ordinal position (0-based index)
        int position = today.ordinal();
        System.out.println("Position in week: " + position);


        // Try different day
        DayOfWeek weekend = DayOfWeek.SATURDAY;
        System.out.println("\nWeekend day: " + weekend);
        System.out.println("Ordinal: " + weekend.ordinal());

    }
}
// Basic enum definition and usage
// Concept: enum - type-safe constants

enum DayOfWeek {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

public class DaysOfWeek {
    public static void main(String[] args) {
        // Basic enum usage
        DayOfWeek today = DayOfWeek.MONDAY;
        System.out.println("Today is: " + today);

        // Compare enums with ==
        if (today == DayOfWeek.MONDAY) {
            System.out.println("Start of work week");
        }

        // Get enum name as string
        String dayName = today.name();
        System.out.println("Day name: " + dayName);

        // Get ordinal position (0-based index)
        int position = today.ordinal();
        System.out.println("Position in week: " + position);


        // Try different day
        DayOfWeek weekend = DayOfWeek.SUNDAY;
        System.out.println("\nWeekend day: " + weekend);
        System.out.println("Ordinal: " + weekend.ordinal());

    }
}
  1. today ← MONDAY

    8public class DaysOfWeek {9    public static void main(String[] args) {10        // Basic enum usage11        DayOfWeek today→ MONDAY = DayOfWeek.MONDAY;12        //@today=DayOfWeek.MONDAY, DayOfWeek.FRIDAY, DayOfWeek.SUNDAY13        System.out.println("Today is: " + todayMONDAY);
    outputToday is: MONDAY
  2. if (today == DayOfWeek.MONDAY)

    15// Compare enums with ==16if (todayMONDAY == DayOfWeek.MONDAY) {17    System.out.println("Start of work week");18}
    outputStart of work week
  3. dayName ← MONDAY, position ← 0, weekend ← SATURDAY

    20// Get enum name as string21String dayName→ MONDAY = today.name();22System.out.println("Day name: " + dayNameMONDAY);2324// Get ordinal position (0-based index)25int position→ 0 = today.ordinal();26System.out.println("Position in week: " + position0);2728//@help h129// Why use enum instead of String?30// 1. Type safety - compiler catches typos31// 2. Can't accidentally assign "Mondy" or "MONNDAY"32// 3. IDE autocomplete shows all valid options33//@end3435// Try different day36DayOfWeek weekend→ SATURDAY = DayOfWeek.SATURDAY;37//@weekend=DayOfWeek.SATURDAY, DayOfWeek.SUNDAY38System.out.println("\nWeekend day: " + weekendSATURDAY);39System.out.println("Ordinal: " + weekend.ordinal());
    outputDay name: MONDAY
    Position in week: 0
    
    Weekend day: SATURDAY
    Ordinal: 5
  1. today ← FRIDAY, dayName ← FRIDAY, position ← 4, weekend ← SATURDAY

    8public class DaysOfWeek {9    public static void main(String[] args) {10        // Basic enum usage11        DayOfWeek today→ FRIDAY = DayOfWeek.FRIDAY;12        System.out.println("Today is: " + todayFRIDAY);13        14        // Compare enums with ==15        if (today == DayOfWeek.MONDAY) {16            System.out.println("Start of work week");17        }18        19        // Get enum name as string20        String dayName→ FRIDAY = today.name();21        System.out.println("Day name: " + dayNameFRIDAY);22        23        // Get ordinal position (0-based index)24        int position→ 4 = today.ordinal();25        System.out.println("Position in week: " + position4);26        27        28        // Try different day29        DayOfWeek weekend→ SATURDAY = DayOfWeek.SATURDAY;30        System.out.println("\nWeekend day: " + weekendSATURDAY);31        System.out.println("Ordinal: " + weekend.ordinal());
    outputToday is: FRIDAY
    Day name: FRIDAY
    Position in week: 4
    
    Weekend day: SATURDAY
    Ordinal: 5
  1. today ← SUNDAY, dayName ← SUNDAY, position ← 6, weekend ← SATURDAY

    8public class DaysOfWeek {9    public static void main(String[] args) {10        // Basic enum usage11        DayOfWeek today→ SUNDAY = DayOfWeek.SUNDAY;12        System.out.println("Today is: " + todaySUNDAY);13        14        // Compare enums with ==15        if (today == DayOfWeek.MONDAY) {16            System.out.println("Start of work week");17        }18        19        // Get enum name as string20        String dayName→ SUNDAY = today.name();21        System.out.println("Day name: " + dayNameSUNDAY);22        23        // Get ordinal position (0-based index)24        int position→ 6 = today.ordinal();25        System.out.println("Position in week: " + position6);26        27        28        // Try different day29        DayOfWeek weekend→ SATURDAY = DayOfWeek.SATURDAY;30        System.out.println("\nWeekend day: " + weekendSATURDAY);31        System.out.println("Ordinal: " + weekend.ordinal());
    outputToday is: SUNDAY
    Day name: SUNDAY
    Position in week: 6
    
    Weekend day: SATURDAY
    Ordinal: 5
  1. today ← MONDAY

    8public class DaysOfWeek {9    public static void main(String[] args) {10        // Basic enum usage11        DayOfWeek today→ MONDAY = DayOfWeek.MONDAY;12        System.out.println("Today is: " + todayMONDAY);
    outputToday is: MONDAY
  2. if (today == DayOfWeek.MONDAY)

    14// Compare enums with ==15if (todayMONDAY == DayOfWeek.MONDAY) {16    System.out.println("Start of work week");17}
    outputStart of work week
  3. dayName ← MONDAY, position ← 0, weekend ← SUNDAY

    19// Get enum name as string20String dayName→ MONDAY = today.name();21System.out.println("Day name: " + dayNameMONDAY);2223// Get ordinal position (0-based index)24int position→ 0 = today.ordinal();25System.out.println("Position in week: " + position0);262728// Try different day29DayOfWeek weekend→ SUNDAY = DayOfWeek.SUNDAY;30System.out.println("\nWeekend day: " + weekendSUNDAY);31System.out.println("Ordinal: " + weekend.ordinal());
    outputDay name: MONDAY
    Position in week: 0
    
    Weekend day: SUNDAY
    Ordinal: 6

enum Name { VALUE1, VALUE2 } defines the allowed values.

enum Type-safe named constants. Fixed set of values known at compile time.

Access enum values

Use enum values in your code.

input
AccessValues.java
Replay: real traced execution (multi-file project)
// Accessing all enum values and converting from string
// Concept: values() - get all enum constants
// Concept: valueOf() - string to enum conversion

enum Priority {
    LOW, MEDIUM, HIGH, URGENT
}

public class AccessValues {
    public static void main(String[] args) {
        // Get all enum values using values()
        Priority[] allPriorities = Priority.values();

        System.out.println("All priority levels:");
        for (Priority p : allPriorities) {
            System.out.println("  " + p);
        }

        // Count total values
        System.out.println("\nTotal priorities: " + allPriorities.length);

        // Convert string to enum using valueOf()
        String input = "HIGH";
        Priority taskPriority = Priority.valueOf(input);
        System.out.println("\nTask priority: " + taskPriority);


        // Check if specific value exists
        Priority current = Priority.MEDIUM;
        boolean isUrgent = (current == Priority.URGENT);
        System.out.println("Is urgent? " + isUrgent);

        // Print with ordinal
        System.out.println("\nPriorities with ordinal:");
        for (Priority p : Priority.values()) {
            System.out.println(p.ordinal() + ": " + p);
        }

    }
}
// Accessing all enum values and converting from string
// Concept: values() - get all enum constants
// Concept: valueOf() - string to enum conversion

enum Priority {
    LOW, MEDIUM, HIGH, URGENT
}

public class AccessValues {
    public static void main(String[] args) {
        // Get all enum values using values()
        Priority[] allPriorities = Priority.values();

        System.out.println("All priority levels:");
        for (Priority p : allPriorities) {
            System.out.println("  " + p);
        }

        // Count total values
        System.out.println("\nTotal priorities: " + allPriorities.length);

        // Convert string to enum using valueOf()
        String input = "LOW";
        Priority taskPriority = Priority.valueOf(input);
        System.out.println("\nTask priority: " + taskPriority);


        // Check if specific value exists
        Priority current = Priority.MEDIUM;
        boolean isUrgent = (current == Priority.URGENT);
        System.out.println("Is urgent? " + isUrgent);

        // Print with ordinal
        System.out.println("\nPriorities with ordinal:");
        for (Priority p : Priority.values()) {
            System.out.println(p.ordinal() + ": " + p);
        }

    }
}
// Accessing all enum values and converting from string
// Concept: values() - get all enum constants
// Concept: valueOf() - string to enum conversion

enum Priority {
    LOW, MEDIUM, HIGH, URGENT
}

public class AccessValues {
    public static void main(String[] args) {
        // Get all enum values using values()
        Priority[] allPriorities = Priority.values();

        System.out.println("All priority levels:");
        for (Priority p : allPriorities) {
            System.out.println("  " + p);
        }

        // Count total values
        System.out.println("\nTotal priorities: " + allPriorities.length);

        // Convert string to enum using valueOf()
        String input = "URGENT";
        Priority taskPriority = Priority.valueOf(input);
        System.out.println("\nTask priority: " + taskPriority);


        // Check if specific value exists
        Priority current = Priority.MEDIUM;
        boolean isUrgent = (current == Priority.URGENT);
        System.out.println("Is urgent? " + isUrgent);

        // Print with ordinal
        System.out.println("\nPriorities with ordinal:");
        for (Priority p : Priority.values()) {
            System.out.println(p.ordinal() + ": " + p);
        }

    }
}
  1. public static void main(String[] args)

    9public class AccessValues {10    public static void main(String[] args) {11        // Get all enum values using values()12        Priority[] allPriorities = Priority.values();13        14        System.out.println("All priority levels:");15        for (Priority p : allPriorities) {
    outputAll priority levels:
  2. for (Priority p : allPriorities)

    pass 1 of 4
    14System.out.println("All priority levels:");15for (Priority pLOW : allPriorities) {16    System.out.println("  " + pLOW);17}
    output  LOW
    All 4 passes — pass 1 is the card above
    passp
    1LOW
    2MEDIUM
    3HIGH
    4URGENT
  3. input ← HIGH, taskPriority ← HIGH, current ← MEDIUM, isUrgent ← false

    19// Count total values20System.out.println("\nTotal priorities: " + allPriorities.length4);2122// Convert string to enum using valueOf()23String input→ HIGH = "HIGH";24//@input="HIGH", "LOW", "URGENT"25Priority taskPriority→ HIGH = Priority.valueOf(inputHIGH);26System.out.println("\nTask priority: " + taskPriorityHIGH);2728//@help h129// valueOf() throws IllegalArgumentException if string doesn't match30// Always match exact case: "HIGH" works, "high" or "High" don't31//@end3233// Check if specific value exists34Priority current→ MEDIUM = Priority.MEDIUM;35boolean isUrgent→ false = (currentMEDIUM == Priority.URGENT);36System.out.println("Is urgent? " + isUrgentfalse);3738// Print with ordinal39System.out.println("\nPriorities with ordinal:");40for (Priority p : Priority.values()) {
    output
    Total priorities: 4
    
    Task priority: HIGH
    Is urgent? false
    
    Priorities with ordinal:
  4. for (Priority p : Priority.values())

    pass 1 of 4
    39System.out.println("\nPriorities with ordinal:");40for (Priority pLOW : Priority.values()) {41    System.out.println(p.ordinal() + ": " + pLOW);42}
    output0: LOW
    All 4 passes — pass 1 is the card above
    passp
    1LOW
    2MEDIUM
    3HIGH
    4URGENT
  1. public static void main(String[] args)

    9public class AccessValues {10    public static void main(String[] args) {11        // Get all enum values using values()12        Priority[] allPriorities = Priority.values();13        14        System.out.println("All priority levels:");15        for (Priority p : allPriorities) {
    outputAll priority levels:
  2. for (Priority p : allPriorities)

    pass 1 of 4
    14System.out.println("All priority levels:");15for (Priority pLOW : allPriorities) {16    System.out.println("  " + pLOW);17}
    output  LOW
    All 4 passes — pass 1 is the card above
    passp
    1LOW
    2MEDIUM
    3HIGH
    4URGENT
  3. input ← LOW, taskPriority ← LOW, current ← MEDIUM, isUrgent ← false

    19// Count total values20System.out.println("\nTotal priorities: " + allPriorities.length4);2122// Convert string to enum using valueOf()23String input→ LOW = "LOW";24Priority taskPriority→ LOW = Priority.valueOf(inputLOW);25System.out.println("\nTask priority: " + taskPriorityLOW);262728// Check if specific value exists29Priority current→ MEDIUM = Priority.MEDIUM;30boolean isUrgent→ false = (currentMEDIUM == Priority.URGENT);31System.out.println("Is urgent? " + isUrgentfalse);3233// Print with ordinal34System.out.println("\nPriorities with ordinal:");35for (Priority p : Priority.values()) {
    output
    Total priorities: 4
    
    Task priority: LOW
    Is urgent? false
    
    Priorities with ordinal:
  4. for (Priority p : Priority.values())

    pass 1 of 4
    34System.out.println("\nPriorities with ordinal:");35for (Priority pLOW : Priority.values()) {36    System.out.println(p.ordinal() + ": " + pLOW);37}
    output0: LOW
    All 4 passes — pass 1 is the card above
    passp
    1LOW
    2MEDIUM
    3HIGH
    4URGENT
  1. public static void main(String[] args)

    9public class AccessValues {10    public static void main(String[] args) {11        // Get all enum values using values()12        Priority[] allPriorities = Priority.values();13        14        System.out.println("All priority levels:");15        for (Priority p : allPriorities) {
    outputAll priority levels:
  2. for (Priority p : allPriorities)

    pass 1 of 4
    14System.out.println("All priority levels:");15for (Priority pLOW : allPriorities) {16    System.out.println("  " + pLOW);17}
    output  LOW
    All 4 passes — pass 1 is the card above
    passp
    1LOW
    2MEDIUM
    3HIGH
    4URGENT
  3. input ← URGENT, taskPriority ← URGENT, current ← MEDIUM, isUrgent ← false

    19// Count total values20System.out.println("\nTotal priorities: " + allPriorities.length4);2122// Convert string to enum using valueOf()23String input→ URGENT = "URGENT";24Priority taskPriority→ URGENT = Priority.valueOf(inputURGENT);25System.out.println("\nTask priority: " + taskPriorityURGENT);262728// Check if specific value exists29Priority current→ MEDIUM = Priority.MEDIUM;30boolean isUrgent→ false = (currentMEDIUM == Priority.URGENT);31System.out.println("Is urgent? " + isUrgentfalse);3233// Print with ordinal34System.out.println("\nPriorities with ordinal:");35for (Priority p : Priority.values()) {
    output
    Total priorities: 4
    
    Task priority: URGENT
    Is urgent? false
    
    Priorities with ordinal:
  4. for (Priority p : Priority.values())

    pass 1 of 4
    34System.out.println("\nPriorities with ordinal:");35for (Priority pLOW : Priority.values()) {36    System.out.println(p.ordinal() + ": " + pLOW);37}
    output0: LOW
    All 4 passes — pass 1 is the card above
    passp
    1LOW
    2MEDIUM
    3HIGH
    4URGENT

EnumName.VALUE - access enum constant. Type-safe, IDE auto-completes.

Enum in switch

Match on enum values cleanly.

light
EnumInSwitch.java
Replay: real traced execution (multi-file project)
// Using enums with switch expressions (Java 14+)
// Concept: switch with enum
// Concept: pattern - state-based behavior

enum TrafficLight {
    RED, YELLOW, GREEN
}

public class EnumInSwitch {
    public static void main(String[] args) {
        // Modern switch expression with enum
        TrafficLight light = TrafficLight.RED;

        String action = switch (light) {
            case RED -> "Stop";
            case YELLOW -> "Slow down";
            case GREEN -> "Go";
        };

        System.out.println("Light: " + light);
        System.out.println("Action: " + action);

        // Classic switch statement
        TrafficLight current = TrafficLight.YELLOW;

        switch (current) {
            case RED:
                System.out.println("\n🔴 RED - Wait for green");
                break;
            case YELLOW:
                System.out.println("\n🟡 YELLOW - Prepare to stop");
                break;
            case GREEN:
                System.out.println("\n🟢 GREEN - Proceed");
                break;
        }


        // Multiple cases same action
        TrafficLight signal = TrafficLight.GREEN;

        boolean shouldWait = switch (signal) {
            case RED, YELLOW -> true;
            case GREEN -> false;
        };

        System.out.println("\nShould wait? " + shouldWait);

    }
}
// Using enums with switch expressions (Java 14+)
// Concept: switch with enum
// Concept: pattern - state-based behavior

enum TrafficLight {
    RED, YELLOW, GREEN
}

public class EnumInSwitch {
    public static void main(String[] args) {
        // Modern switch expression with enum
        TrafficLight light = TrafficLight.YELLOW;

        String action = switch (light) {
            case RED -> "Stop";
            case YELLOW -> "Slow down";
            case GREEN -> "Go";
        };

        System.out.println("Light: " + light);
        System.out.println("Action: " + action);

        // Classic switch statement
        TrafficLight current = TrafficLight.YELLOW;

        switch (current) {
            case RED:
                System.out.println("\n🔴 RED - Wait for green");
                break;
            case YELLOW:
                System.out.println("\n🟡 YELLOW - Prepare to stop");
                break;
            case GREEN:
                System.out.println("\n🟢 GREEN - Proceed");
                break;
        }


        // Multiple cases same action
        TrafficLight signal = TrafficLight.GREEN;

        boolean shouldWait = switch (signal) {
            case RED, YELLOW -> true;
            case GREEN -> false;
        };

        System.out.println("\nShould wait? " + shouldWait);

    }
}
// Using enums with switch expressions (Java 14+)
// Concept: switch with enum
// Concept: pattern - state-based behavior

enum TrafficLight {
    RED, YELLOW, GREEN
}

public class EnumInSwitch {
    public static void main(String[] args) {
        // Modern switch expression with enum
        TrafficLight light = TrafficLight.GREEN;

        String action = switch (light) {
            case RED -> "Stop";
            case YELLOW -> "Slow down";
            case GREEN -> "Go";
        };

        System.out.println("Light: " + light);
        System.out.println("Action: " + action);

        // Classic switch statement
        TrafficLight current = TrafficLight.YELLOW;

        switch (current) {
            case RED:
                System.out.println("\n🔴 RED - Wait for green");
                break;
            case YELLOW:
                System.out.println("\n🟡 YELLOW - Prepare to stop");
                break;
            case GREEN:
                System.out.println("\n🟢 GREEN - Proceed");
                break;
        }


        // Multiple cases same action
        TrafficLight signal = TrafficLight.GREEN;

        boolean shouldWait = switch (signal) {
            case RED, YELLOW -> true;
            case GREEN -> false;
        };

        System.out.println("\nShould wait? " + shouldWait);

    }
}
  1. light ← RED, action ← Stop, current ← YELLOW

    9public class EnumInSwitch {10    public static void main(String[] args) {11        // Modern switch expression with enum12        TrafficLight light→ RED = TrafficLight.RED;13        //@light=TrafficLight.RED, TrafficLight.YELLOW, TrafficLight.GREEN14        15        String action→ Stop = switch (light) {16            case RED -> "Stop";17            case YELLOW -> "Slow down";18            case GREEN -> "Go";19        };20        21        System.out.println("Light: " + lightRED);22        System.out.println("Action: " + actionStop);23        24        // Classic switch statement25        TrafficLight current→ YELLOW = TrafficLight.YELLOW;
    outputLight: RED
    Action: Stop
  2. switch (current)

    27switch (currentYELLOW) {28    case RED:29        System.out.println("\n🔴 RED - Wait for green");
  3. case YELLOW:

    30    break;31case YELLOW:32    System.out.println("\n🟡 YELLOW - Prepare to stop");33    break;34case GREEN:
    output
    🟡 YELLOW - Prepare to stop
  4. signal ← GREEN, shouldWait ← false

    45// Multiple cases same action46TrafficLight signal→ GREEN = TrafficLight.GREEN;4748boolean shouldWait→ false = switch (signal) {49    case RED, YELLOW -> true;50    case GREEN -> false;51};5253System.out.println("\nShould wait? " + shouldWaitfalse);
    output
    Should wait? false
  1. light ← YELLOW, action ← Slow down, current ← YELLOW

    9public class EnumInSwitch {10    public static void main(String[] args) {11        // Modern switch expression with enum12        TrafficLight light→ YELLOW = TrafficLight.YELLOW;13        14        String action→ Slow down = switch (light) {15            case RED -> "Stop";16            case YELLOW -> "Slow down";17            case GREEN -> "Go";18        };19        20        System.out.println("Light: " + lightYELLOW);21        System.out.println("Action: " + actionSlow down);22        23        // Classic switch statement24        TrafficLight current→ YELLOW = TrafficLight.YELLOW;
    outputLight: YELLOW
    Action: Slow down
  2. switch (current)

    26switch (currentYELLOW) {27    case RED:28        System.out.println("\n🔴 RED - Wait for green");
  3. case YELLOW:

    29    break;30case YELLOW:31    System.out.println("\n🟡 YELLOW - Prepare to stop");32    break;33case GREEN:
    output
    🟡 YELLOW - Prepare to stop
  4. signal ← GREEN, shouldWait ← false

    39// Multiple cases same action40TrafficLight signal→ GREEN = TrafficLight.GREEN;4142boolean shouldWait→ false = switch (signal) {43    case RED, YELLOW -> true;44    case GREEN -> false;45};4647System.out.println("\nShould wait? " + shouldWaitfalse);
    output
    Should wait? false
  1. light ← GREEN, action ← Go, current ← YELLOW

    9public class EnumInSwitch {10    public static void main(String[] args) {11        // Modern switch expression with enum12        TrafficLight light→ GREEN = TrafficLight.GREEN;13        14        String action→ Go = switch (light) {15            case RED -> "Stop";16            case YELLOW -> "Slow down";17            case GREEN -> "Go";18        };19        20        System.out.println("Light: " + lightGREEN);21        System.out.println("Action: " + actionGo);22        23        // Classic switch statement24        TrafficLight current→ YELLOW = TrafficLight.YELLOW;
    outputLight: GREEN
    Action: Go
  2. switch (current)

    26switch (currentYELLOW) {27    case RED:28        System.out.println("\n🔴 RED - Wait for green");
  3. case YELLOW:

    29    break;30case YELLOW:31    System.out.println("\n🟡 YELLOW - Prepare to stop");32    break;33case GREEN:
    output
    🟡 YELLOW - Prepare to stop
  4. signal ← GREEN, shouldWait ← false

    39// Multiple cases same action40TrafficLight signal→ GREEN = TrafficLight.GREEN;4142boolean shouldWait→ false = switch (signal) {43    case RED, YELLOW -> true;44    case GREEN -> false;45};4647System.out.println("\nShould wait? " + shouldWaitfalse);
    output
    Should wait? false

Switch on enum is exhaustive. Compiler warns if cases are missing.

Iterate all values

Loop through all enum constants.

IterateValues.java
Replay: real traced execution (multi-file project)
// Iterating through enum values
// Concept: iteration - process all enum constants
// Concept: ordinal - enum position

enum Month {
    JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE,
    JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER
}

public class IterateValues {
    public static void main(String[] args) {
        // Iterate all months
        System.out.println("All months:");
        for (Month m : Month.values()) {
            System.out.println(m);
        }

        // Print with month number (ordinal + 1)
        System.out.println("\nMonths with numbers:");
        for (Month m : Month.values()) {
            int monthNumber = m.ordinal() + 1;  // ordinal is 0-based
            System.out.println(monthNumber + ". " + m);
        }


        // Find specific months
        System.out.println("\nSummer months:");
        for (Month m : Month.values()) {
            if (m.ordinal() >= 5 && m.ordinal() <= 7) {  // June-August
                System.out.println("  " + m);
            }
        }

        // Count months in first quarter
        int q1Count = 0;
        for (Month m : Month.values()) {
            if (m.ordinal() < 3) {  // Jan, Feb, Mar
                q1Count++;
            }
        }
        System.out.println("\nQ1 months: " + q1Count);

        // Get specific month by ordinal
        Month current = Month.values()[3];  // April (index 3)
        System.out.println("Month at index 3: " + current);
    }
}
  1. public static void main(String[] args)

    10public class IterateValues {11    public static void main(String[] args) {12        // Iterate all months13        System.out.println("All months:");14        for (Month m : Month.values()) {
    outputAll months:
  2. for (Month m : Month.values())

    pass 1 of 12
    13System.out.println("All months:");14for (Month mJANUARY : Month.values()) {15    System.out.println(mJANUARY);16}
    outputJANUARY
    All 12 passes — pass 1 is the card above
    passm
    1JANUARY
    2FEBRUARY
    3MARCH
    4APRIL
    5MAY
    6JUNE
    7JULY
    8AUGUST
    9SEPTEMBER
    10OCTOBER
    11NOVEMBER
    12DECEMBER
  3. System.out.println(" Months with numbers:");

    18// Print with month number (ordinal + 1)19System.out.println("\nMonths with numbers:");20for (Month m : Month.values()) {
    output
    Months with numbers:
  4. monthNumber ← 1

    pass 1 of 12
    19System.out.println("\nMonths with numbers:");20for (Month mJANUARY : Month.values()) {21    int monthNumber→ 1 = m.ordinal() + 1;  // ordinal is 0-based22    System.out.println(monthNumber1 + ". " + mJANUARY);23}
    output1. JANUARY
    All 12 passes — pass 1 is the card above
    passmmonthNumber
    1JANUARY1
    2FEBRUARY2
    3MARCH3
    4APRIL4
    5MAY5
    6JUNE6
    7JULY7
    8AUGUST8
    9SEPTEMBER9
    10OCTOBER10
    11NOVEMBER11
    12DECEMBER12
  5. System.out.println(" Summer months:");

    30// Find specific months31System.out.println("\nSummer months:");32for (Month m : Month.values()) {
    output
    Summer months:
  6. for (Month m : Month.values())

    pass 1 of 12
    31System.out.println("\nSummer months:");32for (Month mJANUARY : Month.values()) {33    if (m.ordinal() >= 5 && m.ordinal() <= 7) {  // June-August
    All 12 passes — pass 1 is the card above
    passm
    1JANUARY
    2FEBRUARY
    3MARCH
    4APRIL
    5MAY
    6JUNE
    7JULY
    8AUGUST
    9SEPTEMBER
    10OCTOBER
    11NOVEMBER
    12DECEMBER
  7. if (m.ordinal() >= 5 && m.ordinal() <= 7)

    pass 1 of 3
    32for (Month m : Month.values()) {33    if (m.ordinal() >= 5 && m.ordinal() <= 7) {  // June-August34        System.out.println("  " + mJUNE);35    }
    output  JUNE
    All 3 passes — pass 1 is the card above
    passm
    1JUNE
    2JULY
    3AUGUST
  8. q1Count ← 0

    38// Count months in first quarter39int q1Count→ 0 = 0;40for (Month m : Month.values()) {
  9. for (Month m : Month.values())

    pass 1 of 12
    39int q1Count = 0;40for (Month mJANUARY : Month.values()) {41    if (m.ordinal() < 3) {  // Jan, Feb, Mar
    All 12 passes — pass 1 is the card above
    passm
    1JANUARY
    2FEBRUARY
    3MARCH
    4APRIL
    5MAY
    6JUNE
    7JULY
    8AUGUST
    9SEPTEMBER
    10OCTOBER
    11NOVEMBER
    12DECEMBER
  10. q1Count ← 1

    pass 1 of 3
    40for (Month m : Month.values()) {41    if (m.ordinal() < 3) {  // Jan, Feb, Mar42        q1Count→ 1++;43    }
    All 3 passes — pass 1 is the card above
    passq1Count
    10 1
    21 2
    32 3
  11. current ← APRIL

    44    }45    System.out.println("\nQ1 months: " + q1Count3);46    47    // Get specific month by ordinal48    Month current→ APRIL = Month.values()[3];  // April (index 3)49    System.out.println("Month at index 3: " + currentAPRIL);50}
    output
    Q1 months: 3
    Month at index 3: APRIL

EnumName.values() returns array of all constants.

values() Built-in method returning all enum constants in declaration order.

Compare enums

Use == for enum comparison (not equals).

customerSize
CompareEnums.java
Replay: real traced execution (multi-file project)
// Comparing enum values
// Concept: comparison - enum equality and ordering
// Concept: natural order - based on declaration order

enum Size {
    SMALL, MEDIUM, LARGE, EXTRA_LARGE
}

public class CompareEnums {
    public static void main(String[] args) {
        // Compare with == (recommended)
        Size shirt = Size.MEDIUM;
        Size pants = Size.MEDIUM;

        if (shirt == pants) {
            System.out.println("Same size");
        }

        // Can use equals() but == is better
        boolean sameSize = shirt.equals(pants);
        System.out.println("Using equals(): " + sameSize);


        // Compare ordinal for ordering
        Size small = Size.SMALL;
        Size large = Size.LARGE;

        if (small.ordinal() < large.ordinal()) {
            System.out.println("\nSMALL comes before LARGE");
        }

        // Check if size is at least MEDIUM
        Size customerSize = Size.LARGE;
        boolean qualifiesForDiscount = customerSize.ordinal() >= Size.MEDIUM.ordinal();
        System.out.println("\nCustomer size: " + customerSize);
        System.out.println("Qualifies for bulk discount: " + qualifiesForDiscount);

        // Find max of two sizes
        Size requested = Size.SMALL;
        Size available = Size.MEDIUM;

        Size actualSize = (requested.ordinal() > available.ordinal())
                          ? requested : available;
        System.out.println("\nRequested: " + requested);
        System.out.println("Available: " + available);
        System.out.println("Actual: " + actualSize);

    }
}
// Comparing enum values
// Concept: comparison - enum equality and ordering
// Concept: natural order - based on declaration order

enum Size {
    SMALL, MEDIUM, LARGE, EXTRA_LARGE
}

public class CompareEnums {
    public static void main(String[] args) {
        // Compare with == (recommended)
        Size shirt = Size.MEDIUM;
        Size pants = Size.MEDIUM;

        if (shirt == pants) {
            System.out.println("Same size");
        }

        // Can use equals() but == is better
        boolean sameSize = shirt.equals(pants);
        System.out.println("Using equals(): " + sameSize);


        // Compare ordinal for ordering
        Size small = Size.SMALL;
        Size large = Size.LARGE;

        if (small.ordinal() < large.ordinal()) {
            System.out.println("\nSMALL comes before LARGE");
        }

        // Check if size is at least MEDIUM
        Size customerSize = Size.SMALL;
        boolean qualifiesForDiscount = customerSize.ordinal() >= Size.MEDIUM.ordinal();
        System.out.println("\nCustomer size: " + customerSize);
        System.out.println("Qualifies for bulk discount: " + qualifiesForDiscount);

        // Find max of two sizes
        Size requested = Size.SMALL;
        Size available = Size.MEDIUM;

        Size actualSize = (requested.ordinal() > available.ordinal())
                          ? requested : available;
        System.out.println("\nRequested: " + requested);
        System.out.println("Available: " + available);
        System.out.println("Actual: " + actualSize);

    }
}
// Comparing enum values
// Concept: comparison - enum equality and ordering
// Concept: natural order - based on declaration order

enum Size {
    SMALL, MEDIUM, LARGE, EXTRA_LARGE
}

public class CompareEnums {
    public static void main(String[] args) {
        // Compare with == (recommended)
        Size shirt = Size.MEDIUM;
        Size pants = Size.MEDIUM;

        if (shirt == pants) {
            System.out.println("Same size");
        }

        // Can use equals() but == is better
        boolean sameSize = shirt.equals(pants);
        System.out.println("Using equals(): " + sameSize);


        // Compare ordinal for ordering
        Size small = Size.SMALL;
        Size large = Size.LARGE;

        if (small.ordinal() < large.ordinal()) {
            System.out.println("\nSMALL comes before LARGE");
        }

        // Check if size is at least MEDIUM
        Size customerSize = Size.EXTRA_LARGE;
        boolean qualifiesForDiscount = customerSize.ordinal() >= Size.MEDIUM.ordinal();
        System.out.println("\nCustomer size: " + customerSize);
        System.out.println("Qualifies for bulk discount: " + qualifiesForDiscount);

        // Find max of two sizes
        Size requested = Size.SMALL;
        Size available = Size.MEDIUM;

        Size actualSize = (requested.ordinal() > available.ordinal())
                          ? requested : available;
        System.out.println("\nRequested: " + requested);
        System.out.println("Available: " + available);
        System.out.println("Actual: " + actualSize);

    }
}
  1. shirt ← MEDIUM, pants ← MEDIUM

    9public class CompareEnums {10    public static void main(String[] args) {11        // Compare with == (recommended)12        Size shirt→ MEDIUM = Size.MEDIUM;13        Size pants→ MEDIUM = Size.MEDIUM;
  2. if (shirt == pants)

    15if (shirtMEDIUM == pantsMEDIUM) {16    System.out.println("Same size");17}
    outputSame size
  3. sameSize ← true, small ← SMALL, large ← LARGE

    19// Can use equals() but == is better20boolean sameSize→ true = shirt.equals(pantsMEDIUM);21System.out.println("Using equals(): " + sameSizetrue);2223//@help h124// Use == for enum comparison (simpler, safer)25// equals() works but == is idiomatic for enums26// Enums are singleton per constant27//@end2829// Compare ordinal for ordering30Size small→ SMALL = Size.SMALL;31Size large→ LARGE = Size.LARGE;
    outputUsing equals(): true
  4. if (small.ordinal() < large.ordinal())

    33if (small.ordinal() < large.ordinal()) {34    System.out.println("\nSMALL comes before LARGE");35}
    output
    SMALL comes before LARGE
  5. customerSize ← LARGE, qualifiesForDiscount ← true, requested ← SMALL

    37// Check if size is at least MEDIUM38Size customerSize→ LARGE = Size.LARGE;39//@customerSize=Size.LARGE, Size.SMALL, Size.EXTRA_LARGE40boolean qualifiesForDiscount→ true = customerSize.ordinal() >= Size.MEDIUM.ordinal();41System.out.println("\nCustomer size: " + customerSizeLARGE);42System.out.println("Qualifies for bulk discount: " + qualifiesForDiscounttrue);4344// Find max of two sizes45Size requested→ SMALL = Size.SMALL;46Size available→ MEDIUM = Size.MEDIUM;4748Size actualSize→ MEDIUM = (requested.ordinal() > available.ordinal()) 49                  ? requestedSMALL : availableMEDIUM;50System.out.println("\nRequested: " + requestedSMALL);51System.out.println("Available: " + availableMEDIUM);52System.out.println("Actual: " + actualSizeMEDIUM);
    output
    Customer size: LARGE
    Qualifies for bulk discount: true
    
    Requested: SMALL
    Available: MEDIUM
    Actual: MEDIUM
  1. shirt ← MEDIUM, pants ← MEDIUM

    9public class CompareEnums {10    public static void main(String[] args) {11        // Compare with == (recommended)12        Size shirt→ MEDIUM = Size.MEDIUM;13        Size pants→ MEDIUM = Size.MEDIUM;
  2. if (shirt == pants)

    15if (shirtMEDIUM == pantsMEDIUM) {16    System.out.println("Same size");17}
    outputSame size
  3. sameSize ← true, small ← SMALL, large ← LARGE

    19// Can use equals() but == is better20boolean sameSize→ true = shirt.equals(pantsMEDIUM);21System.out.println("Using equals(): " + sameSizetrue);222324// Compare ordinal for ordering25Size small→ SMALL = Size.SMALL;26Size large→ LARGE = Size.LARGE;
    outputUsing equals(): true
  4. if (small.ordinal() < large.ordinal())

    28if (small.ordinal() < large.ordinal()) {29    System.out.println("\nSMALL comes before LARGE");30}
    output
    SMALL comes before LARGE
  5. customerSize ← SMALL, qualifiesForDiscount ← false, requested ← SMALL

    32// Check if size is at least MEDIUM33Size customerSize→ SMALL = Size.SMALL;34boolean qualifiesForDiscount→ false = customerSize.ordinal() >= Size.MEDIUM.ordinal();35System.out.println("\nCustomer size: " + customerSizeSMALL);36System.out.println("Qualifies for bulk discount: " + qualifiesForDiscountfalse);3738// Find max of two sizes39Size requested→ SMALL = Size.SMALL;40Size available→ MEDIUM = Size.MEDIUM;4142Size actualSize→ MEDIUM = (requested.ordinal() > available.ordinal()) 43                  ? requestedSMALL : availableMEDIUM;44System.out.println("\nRequested: " + requestedSMALL);45System.out.println("Available: " + availableMEDIUM);46System.out.println("Actual: " + actualSizeMEDIUM);
    output
    Customer size: SMALL
    Qualifies for bulk discount: false
    
    Requested: SMALL
    Available: MEDIUM
    Actual: MEDIUM
  1. shirt ← MEDIUM, pants ← MEDIUM

    9public class CompareEnums {10    public static void main(String[] args) {11        // Compare with == (recommended)12        Size shirt→ MEDIUM = Size.MEDIUM;13        Size pants→ MEDIUM = Size.MEDIUM;
  2. if (shirt == pants)

    15if (shirtMEDIUM == pantsMEDIUM) {16    System.out.println("Same size");17}
    outputSame size
  3. sameSize ← true, small ← SMALL, large ← LARGE

    19// Can use equals() but == is better20boolean sameSize→ true = shirt.equals(pantsMEDIUM);21System.out.println("Using equals(): " + sameSizetrue);222324// Compare ordinal for ordering25Size small→ SMALL = Size.SMALL;26Size large→ LARGE = Size.LARGE;
    outputUsing equals(): true
  4. if (small.ordinal() < large.ordinal())

    28if (small.ordinal() < large.ordinal()) {29    System.out.println("\nSMALL comes before LARGE");30}
    output
    SMALL comes before LARGE
  5. customerSize ← EXTRA_LARGE, qualifiesForDiscount ← true, requested ← SMALL

    32// Check if size is at least MEDIUM33Size customerSize→ EXTRA_LARGE = Size.EXTRA_LARGE;34boolean qualifiesForDiscount→ true = customerSize.ordinal() >= Size.MEDIUM.ordinal();35System.out.println("\nCustomer size: " + customerSizeEXTRA_LARGE);36System.out.println("Qualifies for bulk discount: " + qualifiesForDiscounttrue);3738// Find max of two sizes39Size requested→ SMALL = Size.SMALL;40Size available→ MEDIUM = Size.MEDIUM;4142Size actualSize→ MEDIUM = (requested.ordinal() > available.ordinal()) 43                  ? requestedSMALL : availableMEDIUM;44System.out.println("\nRequested: " + requestedSMALL);45System.out.println("Available: " + availableMEDIUM);46System.out.println("Actual: " + actualSizeMEDIUM);
    output
    Customer size: EXTRA_LARGE
    Qualifies for bulk discount: true
    
    Requested: SMALL
    Available: MEDIUM
    Actual: MEDIUM

== is safe and preferred for enums. They're singletons.

Exercise: Practical.java

Build a state machine using enums