Sometimes you may have the scenarion where you want to compare String to enumeration constants.
Like you may have an enum with product codes an you want to check that the passed produce code is one of the predefined product codes or not.
Here one thing to note is directly comparing enum value with a string won't work as they both will be of different types. As example notice in the code snippet given below where enum type d is directly compared with the String, it won't give any output as they will never be equal.
enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
public class EnumDemo {
public static void main(String[] args) {
EnumDemo ed = new EnumDemo();
ed.checkDay("TUESDAY");
}
private void checkDay(String str){
Days[] allDays = Days.values();
for(Days d : allDays){
if(d.equals(str)){
System.out.println(d + "" + d.getDay());
}
}
}
}
Using toString() or name() methods
What you should do in such scenario is to convert enum to string for that you can use toString() method with the enum as toString() method returns the name of this enum constant, as contained in the declaration.
With toString() method
enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
public class EnumDemo {
public static void main(String[] args) {
EnumDemo ed = new EnumDemo();
ed.checkDay("TUESDAY");
}
private void checkDay(String str){
Days[] allDays = Days.values();
for(Days d : allDays){
if(d.toString().equals(str)){
System.out.println(d + "" + d.getDay());
}
}
}
}
That will work as desired and give you the output - TUESDAY 3
Using name() method
Enum class also has a name() method that returns the name of this enum constant, exactly as declared in its enum declaration. Though a word of caution here according to Java docs -
"Most programmers should use the toString() method in preference to this one, as the toString method may return a more user-friendly name. This method is designed primarily for use in specialized situations where correctness depends on getting the exact name, which will not vary from release to release."
Example code
enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
public class EnumDemo {
public static void main(String[] args) {
EnumDemo ed = new EnumDemo();
ed.checkDay("TUESDAY");
}
private void checkDay(String str){
Days[] allDays = Days.values();
for(Days d : allDays){
if(d.name().equals(str)){
System.out.println(d + "" + d.getDay());
}
}
}
}
Using name() method also gives the desired output - TUESDAY 3
That's all for this topic Comparing Enum to String - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
You may also like -