Skip to main content

Built-in Enum Methods

When you create an enum, the Java compiler automatically adds several highly useful methods to your enum class.

Here are the three most important built-in methods you need to know: values(), valueOf(), and ordinal().


1. The values() Method

The values() method returns an array containing all of the values of the enum in the exact order they were declared.

This method is incredibly useful when you need to loop over all the possible constants in an enum.

enum Season {
WINTER,
SPRING,
SUMMER,
FALL,
}

public class LabEnumMethods1 {

public static void main(String[] args) {
System.out.println("All available seasons:");

// Looping through the array returned by values()
for (Season s : Season.values()) {
System.out.println(s);
}
}
}

Output:

All available seasons:
WINTER
SPRING
SUMMER
FALL

2. The valueOf(String) Method

The valueOf() method takes a String and returns the enum constant with that exact name.

It is strictly case-sensitive. If the string doesn't exactly match the name of the constant (including the case), it throws an IllegalArgumentException.

enum Season {
WINTER,
SPRING,
SUMMER,
FALL,
}

public class LabEnumMethods2 {

public static void main(String[] args) {
// Converting a String to an Enum constant
Season current = Season.valueOf("SUMMER");
System.out.println("Current Season is: " + current);

try {
// This will crash! "summer" is lowercase, but the constant is uppercase.
Season wrong = Season.valueOf("summer");
} catch (IllegalArgumentException e) {
System.out.println("Error: Constant not found!");
}
}
}

3. The ordinal() Method

The ordinal() method returns the index (the position) of the enum constant as an integer.

Just like arrays in Java, enum indices are zero-based. The first constant declared has an ordinal of 0, the second has 1, and so on.

enum Status {
PENDING, // Ordinal 0
PROCESSING, // Ordinal 1
COMPLETED, // Ordinal 2
FAILED, // Ordinal 3
}

public class LabEnumMethods3 {

public static void main(String[] args) {
Status status = Status.COMPLETED;

System.out.println("The status is: " + status);
System.out.println("The index of this status is: " + status.ordinal());
}
}

Output:

The status is: COMPLETED
The index of this status is: 2

[!WARNING] While ordinal() is useful, you should generally avoid relying on it for business logic (like saving the ordinal number to a database). If another developer comes along and changes the order of the constants in the source code, all the ordinal values will instantly change, breaking your application!