How to Get the Integer Value in Enum Java

How to Get the Integer Value in Enum Java thumbnail
Aside from the enum value, the integer value of an enum can be useful for identifying the data you're working with.

Enums are a feature added to the Java programming language in Java 1.5. They allow a developer to create a set of values that are closely related, referenced by an understandable name and force the use of a finite number of values. Enums also contain extra data relevant to their type, such as the ordinal value of the enum, the index of where the value is defined in the enum type. This can come in handy in various situations, such as using enums to represent the index of an array or List data type.

Things You'll Need

  • Java SDK
  • Java IDE such as Eclipse or NetBeans is strongly recommended, though not necessary. (This article will assume Eclipse, though the IDE functionality used is extremely general and applicable to all environments.)
Show More

Instructions

    • 1

      Create your enum type. In Eclipse, right click on your project's src folder, select "New" from the context menu, and select "Enum" from the sub-menu. Name your enum whatever you like; this article will use "TestEnum" for simplicity.

    • 2

      Add some values to your enum. If you're not feeling very creative, you can just copy and paste the following:

      public enum TestEnum {

      THE_FIRST_VALUE,

      THE_SECOND_VALUE,

      ANOTHER_VALUE,

      YET_ANOTHER_VALUE;

      }

    • 3

      Add another class to your project -- again, named whatever you like -- and ensure that you have the "public static void main(String[] args)" check box selected.

    • 4

      In your main method, add the following code:

      TestEnum te = TestEnum.ANOTHER_VALUE;

      int intVal = te.ordinal();

      System.out.println("The ordinal for " + te.toString() + " is " + intVal);

      If you run this, you should get console output similar to the following:

      The ordinal for ANOTHER_VALUE is 2

      Note that the ordinal value is zero-based, like array indices; this can be slightly confusing at first if you aren't expecting it.

Tips & Warnings

  • Using the ordinal value of an enum can be useful when working with indexed data structures, like arrays or Lists. For example, you could create an array of strings that are represented by the given enum, then reference the strings in a method like so:

  • public String getString(TestEnum te) {

  • return theStrings[te.ordinal()];

  • }

  • Just to reiterate the point in the last step, keep in mind that the ordinals are zero-based. They're also dependent on the compile-time order of the enum values -- if you move ANOTHER_VALUE up to the first item, you'll get 0 as your output instead of 2.

Related Searches:
  • Photo Credit Ablestock.com/AbleStock.com/Getty Images

Comments

Related Ads

Featured