Enum Common Methods Tutorial

Whenever you create an enumerated list using the enum keyword, the resulting object is an Enum class type (java.lang.Enum). The most useful and common methods that you can invoke on an enum instance are:

  • .name() · Returns a String value of the name of the enum constant.
  • .ordinal() · Return an int value of where the enum constant resides in the list, just like an index in an array.
  • .values() · Returns a populated array of enum type objects.
  • .valueOf(String name) · Returns an enum constant data type matching the string value of the parameter.
Let's jump right into demonstrating these methods in the code below.



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md EnumCommon
C:\Java>cd EnumCommon
C:\Java\EnumCommon>Notepad EnumCommon.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


enum Sizes { SMALL, MEDIUM, LARGE}

class EnumCommon {
    public static void main(String args[]) {
        Sizes sRef = Sizes.MEDIUM;
        System.out.println(sRef.name());
        System.out.println(sRef.ordinal());
        System.out.println();

        sRef = Sizes.valueOf("LARGE");
        System.out.println(sRef.name());
        System.out.println(sRef.ordinal());
        System.out.println();

        Sizes sArray[] = Sizes.values();
        for (Sizes s : sArray){
            System.out.println(s.name());
            System.out.println(s.ordinal());
        }
    }
}

Now switch back to the command prompt (CMD) and type in javac EnumCommon.java and press Enter.
Now type in java EnumCommon and press Enter.


C:\Java\EnumCommon>javac EnumCommon.java
C:\Java\EnumCommon>java EnumCommon
MEDIUM
1

LARGE
2

SMALL
0
MEDIUM
1
LARGE
2


Final thoughts


Tutorials