Sometimes you may have the scenario where you want to compare String to enum type in Java. For example you may have an enum with product codes and 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.
For 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){ Day[] allDays = Day.values(); for(Day d : allDays){ if(d.equals(str)){ System.out.println("Day of week- " + d.name()); } } } }
Comparing String to Enum type in Java
For comparing String to Enum type you should convert enum to string and then compare them. For that you can use toString()
method or name()
method.
- toString()- Returns the name of this enum constant, as contained in the declaration.
- name()- Returns the name of this enum constant, exactly as declared in its enum declaration.
Using toString() method to compare enum to String in Java
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){ Day[] allDays = Day.values(); for(Day d : allDays){ //Comparing if(d.toString().equals(str)){ System.out.println("Day of week- " + d.name()); } } } }
That will work as desired and give you the output - Day of week- TUESDAY
Using name() method to compare enum to String in Java
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."
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){ Day[] allDays = Day.values(); for(Day d : allDays){ if(d.name().equals(str)){ System.out.println("Day of week- " + d.name()); } } } }
Using name() method also gives the desired output - Day of week- TUESDAY
That's all for this topic Comparing Enum to String in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Programs Page
Related Topics
You may also like-