Enumeration in Java allows you to define a set of named values, which can be used as constants in your code. It provides a convenient way to represent a group of related values and enhances the readability and maintainability of your programs.
To declare an enumeration in Java, you use the enum keyword followed by the name of the enumeration type. Inside the curly braces, you list the constants of the enumeration, separated by commas.
enum EnumerationName { CONSTANT1, CONSTANT2, // Additional constants }
enum DayOfWeek { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
To access the constants of an enumeration, you use the dot notation, specifying the enumeration name followed by the constant name.
DayOfWeek today = DayOfWeek.MONDAY; System.out.println("Today is: " + today);
Enumerations are commonly used in switch statements to handle different cases based on the enumeration constant.
DayOfWeek day = DayOfWeek.FRIDAY; switch (day) { case MONDAY: System.out.println("It's Monday. Start of the week."); break; case FRIDAY: System.out.println("It's Friday. Weekend is coming!"); break; // Handle other cases }
You can add methods and fields to an enumeration, allowing you to perform custom operations or associate additional data with the enumeration constants.
enum EnumerationName { CONSTANT1, CONSTANT2, // Additional constants // Methods and fields returnType methodName() { // Method implementation } dataType fieldName; }
enum TrafficLight { RED("Stop"), YELLOW("Caution"), GREEN("Go"); private String message; TrafficLight(String message) { this.message = message; } public String getMessage() { return message; } }
Enumeration in Java provides a powerful way to define a fixed set of named values. It improves the clarity and maintainability of your code by representing related constants as a group. By understanding the syntax and usage of enumerations, you can leverage this feature to enhance the structure and readability of your Java programs.