Java.lang Package Classes

Java Enum - valueOf() Method



The java.lang.Enum.valueOf() method returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type.

Syntax

public static <T extends Enum<T>> T valueOf(Class<T> enumType,
                                            String name)

Here, T is the enum type whose constant is to be returned.


Parameters

enumType Specify the Class object of the enum type from which to return a constant.
name Specify the name of the constant to return.

Return Value

Returns the enum constant of the specified enum type with the specified name.

Exception

  • Throws IllegalArgumentException, if the specified enum type has no constant with the specified name, or the specified class object does not represent an enum type.
  • Throws NullPointerException, if enumType or name is null.

Example:

In the example below, the java.lang.Enum.valueOf() method returns the enum constant of the given enum type with the given name.

import java.lang.*;

public class MyClass {
  
  //creating an enum
  public enum WeekDay{
    MON("1st"), TUE("2nd"), WED("3rd"), THU("4th"), FRI("5th");

    String day;
    WeekDay(String x) {
      day = x;
    }

    String showDay() {
      return day;
    }
  }

  public static void main(String[] args) {
    System.out.println("WeekDay List:");
    for(WeekDay i : WeekDay.values()) {
      System.out.println(i + " is the " + i.showDay() + " day of the week.");
    }

    WeekDay val = WeekDay.valueOf("MON");
    System.out.println("Selected WeekDay = " + val); 

  }
}

The output of the above code will be:

WeekDay List:
MON is the 1st day of the week.
TUE is the 2nd day of the week.
WED is the 3rd day of the week.
THU is the 4th day of the week.
FRI is the 5th day of the week.
Selected WeekDay = MON

❮ Java.lang - Enum