ordinal()
method?The order of an instance of enum
is returned via the ordinal()
function. This instance method reflects the order in the enum
declaration in which the starting constant is given the ordinal 0
in the enum declaration.
This concept is similar to array indexes.
public final int ordinal()
This method accepts no arguments.
This function returns the ordinal of the string constant in the enum
declaration.
enum
and its valuesenum Direction{
UP, DOWN, RIGHT, LEFT;
}
In the enum
declaration above, the ordinal values for different constants are as follows.
Enum | Ordinal Value |
---|---|
UP | 0 |
DOWN | 1 |
RIGHT | 2 |
LEFT | 3 |
public class Main {enum Direction{UP, DOWN, RIGHT, LEFT;}public static void main(String[] args) {System.out.println("Ordinal value for " + Direction.UP.name() + " is " + Direction.UP.ordinal());System.out.println("Ordinal value for " + Direction.DOWN.name() + " is " + Direction.DOWN.ordinal());System.out.println("Ordinal value for " + Direction.RIGHT.name() + " is " + Direction.RIGHT.ordinal());System.out.println("Ordinal value for " + Direction.LEFT.name() + " is " + Direction.LEFT.ordinal());}}