Introduction: Why Enum and String Are Eternal Companions?
\n\nImagine: you are writing a program that accepts commands from a user. The user enters "RED", and your program must understand that this is the color Color.RED. Or you are reading data from a database where the status is stored as the text "ACTIVE", and in the code you have an enum Status.ACTIVE. How do you link a string and an enum? This is one of the most popular questions on Stack Overflow among beginner Java developers — and today we will break it down once and for all.
In this article, you will learn:
\n- \n
- How to get an enum from a string in Java using
valueOf()\n - How to handle the situation when the string is not in the enum (so the program doesn't crash) \n
- How to write your own method for flexible conversion \n
- How to work with case and spaces \n
Let's go!
\n\n1. What is an enum and why convert it to a string?
\n\nEnum (short for enumeration) is a special data type in Java that contains a fixed set of constants. For example, days of the week, colors, order statuses.
\n\npublic enum Color {\n RED, GREEN, BLUE, YELLOW\n}\n\nWorking with enums is convenient: the code becomes readable, and the compiler checks that you are not using a non-existent value. But often data comes from the outside world — from a file, database, or user input — in the form of strings. And then the task arises: how to get an enum from a string in Java?
\n\n2. The Basic Way: The valueOf() Method
\n\nThe simplest and built-in way is to use the static method valueOf(), which every enum has. It takes a string and returns the corresponding enum constant. Important: the strings must match the constant names exactly, including case.
public class Main {\n public static void main(String[] args) {\n String input = "RED";\n Color color = Color.valueOf(input);\n System.out.println("Color: " + color); // Output: Color: RED\n }\n}\n\nenum Color {\n RED, GREEN, BLUE\n}\n\nDoes it work? Yes. But there is a catch. If you pass the string "red" (lowercase) or "PURPLE" (which is not in the enum), Java will throw an IllegalArgumentException. And that means the program will crash. Not good.
3. How to Avoid Errors: Exception Handling
\n\nTo prevent the program from crashing, you need to catch the exception. This is especially important when you get an enum from a string entered by the user.
\n\npublic static Color getColorFromString(String input) {\n try {\n return Color.valueOf(input.toUpperCase());\n } catch (IllegalArgumentException e) {\n System.out.println("Error: color '" + input + "' does not exist!");\n return null; // or a default value\n }\n}\n\npublic static void main(String[] args) {\n String userInput = "blue";\n Color color = getColorFromString(userInput);\n if (color != null) {\n System.out.println("You chose: " + color);\n }\n}\n\nNote: we used input.toUpperCase() — this allows accepting strings in any case. In Java, enum names are conventionally written in uppercase, so this trick almost always works.
4. Advanced Way: Custom Method with a Map
\n\nSometimes the names of constants in an enum do not match what comes from outside. For example, you have an enum with Russian names or with spaces. In such cases, you need to create your own mapping.
\n\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic enum Status {\n ACTIVE("active"),\n INACTIVE("inactive"),\n PENDING("pending");\n\n private final String displayName;\n\n Status(String displayName) {\n this.displayName = displayName;\n }\n