What is the ordinal() method in enum in Java?

What is the 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.

Method signature


public final int ordinal()

Parameters

This method accepts no arguments.

Return value

This function returns the ordinal of the string constant in the enum declaration.

enum and its values

enum 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

Code

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());
}
}

Free Resources