How do I get enum constant value corresponds to a string?

Category: fundamental, viewed: 2147 time(s).

The valueOf() method of an enum type allows you to get an enum constant that the value corresponds to the specified string. When we pass a string that not available in the enum an exception will be thrown.

package org.kodejava.example.fundametal;

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

public class EnumValueOfTest {
    public static void main(String[] args) {
        //
        // Using valueOf() method we can get an enum constant whose
        // value corresponds to the string passed as the parameter.
        //
        Day day = Day.valueOf("SATURDAY");
        System.out.println("Day = " + day);
        day = Day.valueOf("WEDNESDAY");
        System.out.println("Day = " + day);

        try {
            //
            // The following line will produce an exception because the
            // enum type does not contains a constant named JANUARY.
            //
            day = Day.valueOf("JANUARY");
            System.out.println("Day = " + day);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }
}
Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Uncensored Newsgroups
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Java Training

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats