In Java, an enum (enumeration) is a special type that defines a set of constants. Enums are used to represent fixed sets of values, such as days of the week, months, status codes, etc. Enum constants are implicitly public
, static
, and final
. They are typically used when a variable can only take one of a few predefined values. Here's an overview of Java enums:
enum
keyword followed by the enum name.{}
.Example of declaring an enum:
public enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
Example of using enums:
public class Main { public static void main(String[] args) { Day today = Day.MONDAY; System.out.println("Today is " + today); // Output: Today is MONDAY // Enums can be used in switch statements switch (today) { case MONDAY: System.out.println("It's the first day of the week"); break; case FRIDAY: System.out.println("It's almost the weekend"); break; default: System.out.println("Just another day"); } } }
Example of enums with constructors and methods:
public enum Day { MONDAY("Monday"), TUESDAY("Tuesday"), WEDNESDAY("Wednesday"), THURSDAY("Thursday"), FRIDAY("Friday"), SATURDAY("Saturday"), SUNDAY("Sunday"); private final String displayName; private Day(String displayName) { this.displayName = displayName; } public String getDisplayName() { return displayName; } } public class Main { public static void main(String[] args) { Day today = Day.MONDAY; System.out.println("Today is " + today.getDisplayName()); // Output: Today is Monday } }