Provider values() method in Java with Examples


The values() method is a built-in method in Java that is used to return an array containing all the values of an enum type in the order they are declared. This method is defined in the Enum class and is automatically inherited by all enum types.

Syntax:

public static EnumType[] values()

Here, EnumType is the name of the enum type for which we want to retrieve all the values.

Example: Let's consider an enum type DaysOfWeek that represents the days of the week.

enum DaysOfWeek {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}

To retrieve all the values of this enum type, we can use the values() method as follows:

DaysOfWeek[] days = DaysOfWeek.values();

This will return an array containing all the values of the DaysOfWeek enum type in the order they are declared.

We can also use a for-each loop to iterate over the array and print the values:

for (DaysOfWeek day : days) {
    System.out.println(day);
}

Output:

MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY

Another example: Let's consider an enum type Colors that represents some colors.

enum Colors {
    RED, GREEN, BLUE;
}

To retrieve all the values of this enum type, we can use the values() method as follows:

Colors[] colors = Colors.values();

This will return an array containing all the values of the Colors enum type in the order they are declared.

We can also use a for loop to iterate over the array and print the values:

for (int i = 0; i < colors.length; i++) {
    System.out.println(colors[i]);
}

Output:

RED
GREEN
BLUE


About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.