SupportWriter space ↗
← Back to the journal
Basic

How do I get ordinal value of enum constant?

This example demonstrate the use of enum ordinal() method to get the ordinal value of an enum constant. package org.kodejava.basic; enum Color { RED, GREEN, BLUE } public class EnumOrdinal { public static void main(String[] args) { // Gets the ordinal of this enumeration constant (its // position in its enum declaration, where the initial […]

DWayan · 07 Aug 2009 · 1 min read

Article by Wayan · Source: Kode Java ↗

This example demonstrate the use of enum ordinal() method to get the ordinal value of an enum constant.

package org.kodejava.basic;

enum Color {
    RED, GREEN, BLUE
}

public class EnumOrdinal {
    public static void main(String[] args) {
        // Gets the ordinal of this enumeration constant (its
        // position in its enum declaration, where the initial 
        // constant is assigned an ordinal of zero)
        System.out.println("Color.RED  : " + Color.RED.ordinal());
        System.out.println("Color.GREEN: " + Color.GREEN.ordinal());
        System.out.println("Color.BLUE : " + Color.BLUE.ordinal());
    }
}

The program print the following result:

Color.RED  : 0
Color.GREEN: 1
Color.BLUE : 2
← Explore more notes