Java Enums are a special type of data type that allow developers to define a set of named constants. Enums were introduced in Java 5 and have since become a popular feature in the language. They provide a way to define a fixed set of values that can be used throughout an application.
Enums are defined using the enum
keyword and can contain a list of constants. Each constant is defined using the public static final
keywords and is separated by a comma. Here is an example of an enum:
public enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
In this example, we have defined an enum called Day
that contains seven constants representing the days of the week. These constants can be used throughout the application to represent the days of the week.
Enums can also have methods and constructors. Here is an example of an enum with a constructor:
public enum Color {
RED(255, 0, 0),
GREEN(0, 255, 0),
BLUE(0, 0, 255);
private int r;
private int g;
private int b;
private Color(int r, int g, int b) {
this.r = r;
this.g = g;
this.b = b;
}
public int getR() {
return r;
}
public int getG() {
return g;
}
public int getB() {
return b;
}
}
In this example, we have defined an enum called Color
that contains three constants representing the primary colors. Each constant has a constructor that takes three integer values representing the red, green, and blue values of the color. The enum also has three methods that return the red, green, and blue values of the color.
Enums can be used in switch statements just like any other data type. Here is an example:
public void printDay(Day day) {
switch (day) {
case MONDAY:
System.out.println("Monday");
break;
case TUESDAY:
System.out.println("Tuesday");
break;
case WEDNESDAY:
System.out.println("Wednesday");
break;
case THURSDAY:
System.out.println("Thursday");
break;
case FRIDAY:
System.out.println("Friday");
break;
case SATURDAY:
System.out.println("Saturday");
break;
case SUNDAY:
System.out.println("Sunday");
break;
}
}
In this example, we have defined a method called printDay
that takes a Day
enum as a parameter. The method uses a switch statement to print the name of the day.
Enums can also be used in collections. Here is an example:
List<Color> colors = new ArrayList<>();
colors.add(Color.RED);
colors.add(Color.GREEN);
colors.add(Color.BLUE);
In this example, we have defined a list of Color
enums and added the three primary colors to the list.
Enums provide a powerful way to define a fixed set of values that can be used throughout an application. They are easy to use and provide a type-safe way to represent constants. If you are not using enums in your Java applications, you are missing out on a powerful feature of the language.