Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Enum.ordinal — a constant's declaration position

Enum.ordinal returns an enum constant's zero-based declaration position. Do not treat it as a persistent identifier.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

public final int ordinal()
// Usage: constant.ordinal()

Enum.ordinal is a no-argument instance method with the signature public final int ordinal(). It returns a constant's position in its enum declaration: the first has 0, the second 1. The final modifier prevents overriding it.

This is a position, not a name or business code. Reordering constants or inserting an earlier constant changes the affected numbers. Therefore, do not store them as persistent database or protocol identifiers; define an explicit, stable code instead.

The documentation identifies structures such as EnumSet and EnumMap as intended uses, rather than typical application logic. In the example, Stage.NEW, Stage.ACTIVE, and Stage.DONE have positions 0, 1, and 2, respectively.

Examples

public class Main {
    enum Stage { NEW, ACTIVE, DONE }

    public static void main(String[] args) {
        System.out.println(Stage.NEW.ordinal());
        System.out.println(Stage.ACTIVE.ordinal());
        System.out.println(Stage.DONE.ordinal());
    }
}

Result

0
1
2

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources