java values( ) method

There is no standard values() method defined in the Java programming language itself. However, starting from Java 5, the values() method is commonly associated with enumerations (enums).

Enumerations (Enums) in Java:

Enums in Java are a way to create a set of named constant values, and they are declared using the enum keyword. Enumerations automatically come with some built-in methods, and one of them is values().

Example:

enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

public class EnumExample {
    public static void main(String[] args) {
        // Using values() to get an array of all enum constants
        Day[] days = Day.values();

        // Iterating over the enum constants
        for (Day day : days) {
            System.out.println(day);
        }
    }
}

In this example, Day.values() returns an array containing all the enum constants defined in the Day enum.

Custom values() Method:

If you encounter a values() method in a context other than enums, it could be a custom method defined by the developer within a class or an API. It’s not a standard method in the Java language itself.

Example (Custom values() Method):

public class CustomValuesExample {
    private String[] values;

    public CustomValuesExample(String... values) {
        this.values = values;
    }

    public String[] values() {
        return values;
    }

    public static void main(String[] args) {
        CustomValuesExample example = new CustomValuesExample("One", "Two", "Three");

        // Using custom values() method
        String[] customValues = example.values();

        // Iterating over custom values
        for (String value : customValues) {
            System.out.println(value);
        }
    }
}

In this example, CustomValuesExample has a custom values() method that returns an array of strings.

If you encountered the term “values()” in a specific context or library, it would be helpful to refer to the documentation of that particular library or API to understand the purpose and behavior of the values() method in that context.

The values( ) method returns an array that contains a list of the enumeration constants.

Example of values() method

enum Apple {
Jonathan, GoldenDel, RedDel, Winesap, Cortland
}

class EnumDemo2 {
public static void main(String args[])
{
Apple ap;
System.out.println(“Here are all Apple constants:”);
// use values()
Apple allapples[] = Apple.values();
for(Apple a : allapples)
System.out.println(a);
System.out.println();
}
}

The output from the program

Here are all Apple constants:
Jonathan
GoldenDel
RedDel
Winesap
Cortland

Leave a Comment