Java Program to Lookup enum by String value
What is enum in Java?
An enum is a special type of data type in Java that enables you to define a set of named constants. An enum is used to represent a fixed set of constants, such as days of the week, months of the year. An enum is essentially a class that has a fixed set of instances, and each instance represents a specific constant value.
In this Article, we will write a program to Lookup enum by String Value.
enum class in Java :
In Java, an enum is a special data type that defines a set of named constants. An enum class is a class that is declared using the enum keyword. Enums are useful when you have a limited set of values that a variable can take, and you want to make sure that only valid values are assigned to that variable.
Example:
enum DaysOfWeek { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
In the above example, DaysOfWeek is an enum class that defines the seven days of the week as named constants. Each constant has a name (e.g. MONDAY) and an integer value that is assigned automatically. You can use the constants defined in an enum class just like any other variable
Example:
DaysOfWeek today = DaysOfWeek.MONDAY;
Program to Lookup enum by String value :
// Importing all the required Packages import java.util.*; // enum creation for colors enum Color{ // constants defined in an enum RED, GREEN, BLUE } public class Main{ // function definition to return str value public static Color fromString(String str){ for (Color c : Color.values()) { if (c.name().equals(str)) { return c; } } throw new IllegalArgumentException("No such color: " + str); } public static void main(String[] args){ // Initializing the String variable String str = "RED"; Color color = fromString(str); System.out.println("The color is: " + color); } }
Output: The color is: RED
Explanation:
In this example, the fromString method takes a string argument and loops through all the values of the Color enum. If a matching string representation is found, the corresponding enum value is returned. If no match is found, an IllegalArgumentException is thrown. The main method demonstrates how to use the fromString method to look up an enum value by its string representation.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment