Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· OpenAIAi2 WildChat-4.8M (AI2)

in java, how to use constants in switch

  1. User

    in java, how to use constants in switch

  2. Assistant

    statements?

    To use constants in switch statements in Java, you must declare the constants before the switch statement. Here's an example:

    public static final int MONDAY = 1;
    public static final int TUESDAY = 2;
    public static final int WEDNESDAY = 3;
    public static final int THURSDAY = 4;
    public static final int FRIDAY = 5;
    public static final int SATURDAY = 6;
    public static final int SUNDAY = 7;
    
    public static void main(String[] args) {
        int dayOfWeek = MONDAY;
    
        switch (dayOfWeek) {
            case MONDAY:
                System.out.println("It's Monday!");
                break;
            case TUESDAY:
                System.out.println("It's Tuesday!");
                break;
            case WEDNESDAY:
                System.out.println("It's Wednesday!");
                break;
            case THURSDAY:
                System.out.println("It's Thursday!");
                break;
            case FRIDAY:
                System.out.println("It's Friday!");
                break;
            case SATURDAY:
                System.out.println("It's Saturday!");
                break;
            case SUNDAY:
                System.out.println("It's Sunday!");
                break;
            default:
                System.out.println("Invalid day of week.");
        }
    }
    

    In this example, we have defined constants for each day of the week using the final modifier. We then declare a variable dayOfWeek and assign it the value of MONDAY.

    We then use a switch statement to check the value of dayOfWeek and execute the corresponding code block based on the constant value.

    If the value of dayOfWeek is not one of the constants defined, the default case will be executed and "Invalid day of week." will be printed to the console.