java enum


In Java, an enum is a special data type that represents a fixed set of values. An enum is essentially a class that has a fixed set of instances, and each instance represents one of the values that the enum can take.

Here is an example of how to define an enum in Java:

public enum Color {

This code defines an enum called Color with three values: RED, GREEN, and BLUE.

You can use an enum in your code just like any other data type. For example, you can use it to declare a variable:

Color favoriteColor = Color.GREEN;

You can also use an enum in a switch statement:

switch (favoriteColor) {
  case RED:
    System.out.println("Your favorite color is red.");
  case GREEN:
    System.out.println("Your favorite color is green.");
  case BLUE:
    System.out.println("Your favorite color is blue.");

An enum can also have additional properties and methods, just like a regular class. For example, you can define a toString() method to return a string representation of an enum value:

public enum Color {
  RED("#FF0000"), GREEN("#00FF00"), BLUE("#0000FF");

  private final String hexCode;

  private Color(String hexCode) {
    this.hexCode = hexCode;

  public String getHexCode() {
    return hexCode;

  public String toString() {
    return name() + " (" + hexCode + ")";

This enum defines a property called hexCode that represents the hexadecimal code of each color, and a getHexCode() method that returns the hex code of a color. It also overrides the toString() method to return a string representation of a color that includes its name and hex code.

Enums are useful for representing a fixed set of values, such as the days of the week, the months of the year, or a set of predefined options. They can make your code more readable and maintainable by providing a clear and concise way to represent these values.

For more information on enums in Java, you can refer to the Java documentation: