Friday, 9 October 2015

valueOf method of enum



Enum valueOf() is a static method which takes a string argument and can be used to convert a String into enum.

valueOf(String) method of enum will throw "Exception in thread "main" java.lang. IllegalArgumentException: No enum const class" if you supply any string other than enum values.


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

public class EnumTest {
      public static void main(String[] args) {
            Day day1 = Day.valueOf("MONDAY");
            System.out.println(day1);
           
            Day day2 = Day.valueOf("tuesday");
            System.out.println(day2);
      }
}
Output:
MONDAY
Exception in thread "main" java.lang.IllegalArgumentException: No enum constant Day.tuesday
      at java.lang.Enum.valueOf(Unknown Source)
      at Day.valueOf(EnumTest.java:1)
      at EnumTest.main(EnumTest.java:12)


No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...