gpt-3.5-turbo-0301· OpenAI
WildChat-4.8M (AI2)
in java, how to use constants in switch
- User
in java, how to use constants in switch
- 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
finalmodifier. We then declare a variabledayOfWeekand assign it the value ofMONDAY.We then use a switch statement to check the value of
dayOfWeekand execute the corresponding code block based on the constant value.If the value of
dayOfWeekis not one of the constants defined, the default case will be executed and "Invalid day of week." will be printed to the console.