Using Enum values as String literals

To use the values of an enum as string literals in Java, you can use the name() method of the Enum class. This method returns the name of the enum value as a string.

For example, consider the following enum:

public enum Color {
    RED,
    GREEN,
    BLUE
}

To use the values of this enum as string literals, you can do the following:

String red = Color.RED.name();
String green = Color.GREEN.name();
String blue = Color.BLUE.name();

This will assign the strings "RED", "GREEN", and "BLUE" to the variables red, green, and blue, respectively.

You can also use the toString() method of the Enum class to get a string representation of an enum value. This method is defined in the Object class and is inherited by all enums, so it will return the name of the enum value by default. However, you can override the toString() method in your enum if you want to return a different string representation.

For example:

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

    private String code;

    private Color(String code) {
        this.code = code;
    }

    @Override
    public String toString() {
        return code;
    }
}

In this example, the toString() method returns the hex code of the color, rather than the name of the enum value. You can then use the toString() method to get a string representation of the enum value:

String red = Color.RED.toString();
String green = Color.GREEN.toString();
String blue = Color.BLUE.toString();

This will assign the strings "#FF0000", "#00FF00", and "#0000FF" to the variables red, green, and blue, respectively.