Sobes.tech
Senior

What predefined methods are available in enum?

sobes.tech AI

Answer from AI

In Java, each enum implicitly inherits from the class java.lang.Enum, which provides several predefined methods:

  • values() — returns an array of all enum constants in the order they are declared.
  • valueOf(String name) — returns the enum constant with the specified name, or throws an IllegalArgumentException if no such constant exists.
  • name() — returns the name of the enum constant as a string.
  • ordinal() — returns the ordinal number of the constant (starting from 0).
  • compareTo(E o) — compares two constants by their ordinal number.
  • toString() — returns the string representation of the constant (by default, the same as name()).

Example usage:

enum Color { RED, GREEN, BLUE }

public class TestEnum {
    public static void main(String[] args) {
        for (Color c : Color.values()) {
            System.out.println(c.name() + " ordinal: " + c.ordinal());
        }

        Color green = Color.valueOf("GREEN");
        System.out.println("ValueOf GREEN: " + green);
    }
}
What predefined methods are available in enum? — Java - sobes.tech