Course contentsShow
← Java
Lesson 606 of 2,87014. EnumerationsFree lesson

The ordinal() Method: Zero-Based Enum Indexing

Learn how ordinal() returns the enum constant's position in its declaration order, starting from zero.

The ordinal() Method: Zero-Based Enum Indexing

What you'll learn: How to retrieve an enum constant's position in its declaration order using ordinal().

Every enum constant in Java has a hidden numeric index that reflects where it appears in the enum declaration. The ordinal() method returns this position as an integer, starting from zero for the first constant.

How Enum Indexing Works

Think of enum constants as items in a numbered list, just like array indices. The first constant is at position 0, the second at position 1, and so on. Java automatically assigns these positions based on declaration order.

enum Priority {
    LOW,      // ordinal 0
    MEDIUM,   // ordinal 1
    HIGH      // ordinal 2
}

Priority p = Priority.MEDIUM;
System.out.println(p.ordinal()); // Prints: 1

Practical Examples

You can use ordinal() to compare enum constants numerically or map them to array indices:

enum Status {
    PENDING, IN_PROGRESS, COMPLETED, CANCELLED
}

Status current = Status.COMPLETED;
System.out.println("Position: " + current.ordinal()); // 2

// Comparing priorities
Priority p1 = Priority.LOW;
Priority p2 = Priority.HIGH;
if (p2.ordinal() > p1.ordinal()) {
    System.out.println("HIGH has higher priority than LOW");
}

Important Cautions

Warning: The ordinal() value changes if you reorder enum constants or add new ones in between. Never persist ordinal values to databases or files—they're fragile and meant primarily for internal use by Java (like in EnumSet and EnumMap implementations).

Key Takeaway: The ordinal() method returns the zero-based position of an enum constant in its declaration order, useful for indexing or comparison but unreliable for persistence or external contracts.