Methods of enum Class

There are some predefined methods in enum classes that are readily available for use.

  1. ordinal() method

    The ordinal() method returns the position of an enum constant. For example, ordinal(SMALL). This statement returns returns 0 as output.

  2. compareTo() Method

    The compareTo() method compares the enum constants based on their ordinal value. For example, Size.SMALL.compareTo(Size.MEDIUM) will return ordinal(SMALL) - ordinal(MEDIUM).

  3. toString() Method

    The toString() method returns the string representation of the enum constants. For example, SMALL.toString() will output "SMALL".

  4. name() Method

    The name() method returns the defined name of an enum constant in string form. The returned value from the name() method is final. For example, name(SMALL) returns "SMALL".

  5. valueOf() Method

    The valueOf() method takes a string and returns an enum constant having the same string name. For example, Size.valueOf("SMALL") returns constant SMALL.

  6. values() Method

    The values() method returns an array of enum type containing all the enum constants. For example, Size[] enumArray = Size.value();.