Home » Java programming language

Java Enum valueOf() method with example

Enum Class valueOf() method: Here, we are going to learn about the valueOf() method of Enum Class with its syntax and example.
Submitted by Preeti Jain, on December 10, 2019

Enum Class valueOf() method

  • valueOf() method is available in java.lang package.
  • valueOf() method is used to retrieve the enum constants of the given parameter en_ty(enum type) with the given parameter en_name(enum name) and we need to remember one thing the enum name specified in the method must be the same as declared as enum constant in this enum type.
  • valueOf() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • valueOf() method may throw an exception at the time of retrieving enum constants:
    • IllegalArgumentException: When the given enum type does not contain enum constants with the given name.
    • NullPointerException: When the given first parameter represents null.

Syntax:

    public static T valueOf(Class<T> en_ty , String en_name);

Parameter(s):

  • Class<T> en_ty – represents the Class object of the enum type which return a constant.
  • String en_name – represents the name of enum constants.

Return value:

The return type of this method is T, it returns enum constant along with the given enum name.

Example:

// Java program to demonstrate the example 
// of T valueOf(Class<T> en_ty , String en_name)
// method of Enum 

enum Month {
    JAN,
    FEB,
    MAR,
    APR,
    MAY;
}

public class ValueOf {
    public static void main(String args[]) {

        Month m1 = Month.valueOf("JAN");
        Month m2 = Month.valueOf("FEB");
        Month m3 = Month.valueOf("MAR");
        Month m4 = Month.valueOf("APR");
        Month m5 = Month.valueOf("MAY");

        System.out.println("Display value: ");

        // By using valueOf() method is to return the value of
        // enum constant 
        System.out.println("Month.valueOf(JAN) " + " " + m1.toString());
        System.out.println("Month.valueOf(FEB) " + " " + m2.toString());
        System.out.println("Month.valueOf(MAR)" + " " + m3.toString());
        System.out.println("Month.valueOf(APR)" + " " + m4.toString());
        System.out.println("Month.valueOf(MAY)" + " " + m5.toString());
    }
}

Output

Display value: 
Month.valueOf(JAN)  JAN
Month.valueOf(FEB)  FEB
Month.valueOf(MAR) MAR
Month.valueOf(APR) APR
Month.valueOf(MAY) MAY


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.