The enum method valueOf() used to retrieve the constant of enum type with the specified name. It expects a string as parameter that represents a name of enum constant. It returns constant of enum type of specified name.
1 public static com.java.Level valueOf(String name)
name : It is a name of enum constant string representation.
return : It returns a constant of enum type with the specified name, if not found, it throws IllegalArgumentException.
1 package com.java;
2
3 enum Level {
4 LOW, MEDIUM, HIGH;
5 }
6
7 public class Example {
8
9 public static void main(String[] args) {
10
11 System.out.println(Level.valueOf("LOW"));
12 System.out.println(Level.valueOf("HIGH"));
13 }
14 }
In the above example, an enum method valueOf() method called by passing a string representation of enum constant. It returns an enum type constant that converted to string internally by println() method and print.
Compare enum constants
1 package com.java;
2
3 enum Level {
4 LOW, MEDIUM, HIGH;
5 }
6
7 public class Example {
8
9 public static void main(String[] args) {
10
11
12 Level lv = Level.valueOf("MEDIUM");
13 if(lv == Level.MEDIUM) {
14 System.out.println("Enum type constants are same.");
15 } else {
16 System.out.println("Enum type constants are not same.");
17 }
18 }
19 }
In the above example, an enum method valueOf() called by passing a enum name that returns enum type constant. An enum object and constant are compared using double equal operator that return boolean value true, as both refer the same constant. It executes if block and print message.
1 Enum type constants are same.
Related options for your search