×

How to Convert String to enum in Java?

In this article, we shall gain the complete knowledge about how to convert the string to enum in Java. The complete process that happens in the approach shall be discussed and each and every method shall also be discussed.

String

Strings are collections of characters that are frequently used in Java programming. Objects in the programming language Java include strings.

For creating and manipulating strings, the Java platform offers the String class.

Now let us acknowledge about the Enum in java.

Enum

A data type in Java called Enum has a predetermined set of constants.

Java Enums can be compared to classes that contain a predetermined collection of constants (a variable that does not change). Implicitly, the Java enumeration constants always static and final. It has been accessible since JDK 1.5.

Enums are employed to design custom data types, much like classes. In Java, an Enum is defined using the Enum data type, also referred to as the Enumerated Data Type. Enumeration of Java is much more powerful than it is in C/C++. Here, we have the option of defining an Enum either within or outside of the class.

Now let us go through how the conversion process occurs.

Approach

With the help of the Enum.valueOf() method, you may generate Enum from a String. ValueOf(), along with the methods values(), name(), and cardinal(), is a static method that is automatically added to every Enum class during compilation. If String is not the same as the specified Enum, the code will throw the error "java.lang.IllegalArgumentException: No enum const class." The same method can be applied to turn a string into an Enum instance.

String constants have been supported in switch cases in Java since version 7, although Enum is usually recommended across both Integer and Character constants since it offers type safety.

In the context of String nor Integer, the compiled code will check if a variable is of the appropriate version but it can't access values, thus you should choose Enum to specify a very well-fixed number of items. The compiler will verify that an invalid value is not supplied.

Here is a Java code sample for converting a String to an Enum. It exemplifies both methods for generating Enums in Java from Strings that we've covered thus far. Any String can be converted to its corresponding Enum using the same method. To prevent Java's IllegalArgumentException, always be sure to give the right String.

Another way to convert a string to an enum is to use the values() method to iterate through all of the specified enum instances, then use equals to compare the provided string to each one (). Despite the fact that it works well, the approach uses more code than Enum.valueOf ().

Example

Let us create an enum with name Vehicles with 5 constants representing models of 5 different scoters with their prices as values, as shown below -

enum Vehicles {
   // variables with values
   ACTIVA125(80000), ACTIVA5G(70000), ACCESS125(75000), VESPA(90000), TVSJUPITER(75000); //Instance variable
   private int price;
   //Constructor to set the instance variable's value
   Vehicles(int price) {
      this.price = price;
   }
   // Static method to display the price
   public int getPrice(){
      return this.price;
   }
}

The Java program below takes a String value out from users, uses the method to turn into an Enum constants of type Vehicles, and then displays the amount (price) of the chosen constant.

File name: Enumeration.java

public class Enumeration {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Available scoters: [activa125, activa5g, access125, vespa, tvsjupiter]");
      System.out.println("Enter the name of required scoter: ");
      String name = sc.next();
      Vehicles v = Vehicles.valueOf(name.toUpperCase());
      System.out.println("Price: "+v.getPrice());
   }
}

Output

Available scoters: [activa125, activa5g, access125, vespa, tvsjupiter]
Enter the name of required scoter:
activa125
Price: 80000

For each method call thus far, we have iterated over through the constant values. We have additional possibilities for comparison thanks to iteration. For instance, we can disregard case and compare the provided value to the name property.

Conclusion

That concludes the section on creating Enums in Java from Strings. Java programmers must be aware with this method to quickly convert String into Enum since it is a fairly common requirement. In conclusion, choose Enum above String to achieve compile-time verification and type safety, but keep in mind that String is a generic type and that you can save your information in the database as String, which will then all be transformed to Enum at runtime.


Related Topics

Diamond problem in Java

The Diamond Problem in Java is connected to multiple inheritances. It is also referred to as the "deadly diamond dilemma" or even the "deadly diamond of death”. The solution for...

5 minutes read.

Packages Program in java

Let us know what package is in the Java programming language, and later we will learn about types of packages and how to define a package. How to import Java...

4 minutes read.

Java Math log() Method

The log() method of Math class returns the natural logarithmic value for the specified double argument. Syntax: public static double log(double a) Parameters: The parameter ‘a’ represents the value. Return Value: The log() method returns the...

1 minute read.

Inheritance Program in Java

Inheritance Program in Java Inheritance is one of the important pillars of Object-Oriented Programming that facilitates parent-child relationships in programming. Using inheritance, we can create a new class with the help...

7 minutes read.

Java Thread Lifecycle: States and Stages

Multithreading Multithreading is one of the most important features in object-oriented programming, and this multithreading can be implemented by various object-oriented programming languages like Java, Python, and C++. A multithreaded process...

7 minutes read.

User Defined Exception in Java

An exception is an error (run time error) that happened while a program was being executed. The program stops abruptly whenever the Exception occurs, and the code after the line...

3 minutes read.

Dutch National Flag Problem in Java

Dutch National Flag (DNF) is a programming issue that Edsger Dijkstra put up. The white, red, and blue hues make up the Dutch flag. The goal is to haphazardly set...

6 minutes read.

Java Read File Line by line

Java provides two options to read files line by line. Each option offers different benefits and has its own set of drawbacks. Following are the ways through which on accomplish...

5 minutes read.

Java Program to remove duplicate characters in a string

In strings, we can find many characters present one or more times in a string; accessing a particular character is difficult due to repetition. Duplicate characters will present in the...

5 minutes read.

Operators in Java

There is a good operator environment provided by Java. These operators are divided into four different groups i.e. arithmetic, bitwise, relational, and logical. There are other operators also available to...

7 minutes read.

How to enable java in chrome

The Java module is huge for the Java Runtime Environment (JRE). It permits a program to work with the Java stage to run Java applets. Essentially, each of the undertakings connect...

3 minutes read.

Stack Program in Java

Stack Program in Java The Stack class is part of the collection framework that inherits the Vector class. Thus, the Stack class can also be called a subclass of the Vector...

5 minutes read.

Blockchain in Java

Blockchain is a continuously expanding ledger that maintains an immutable, secure, and chronological record of all transactions that have ever occurred. It can be utilized to securely transfer money, assets,...

9 minutes read.

Java Integer toUnsignedString() method

The toUnsignedString() method of Java Integer class returns a string representation of the argument as an unsigned decimal value. The second syntax returns a string representation of the given argument as...

2 minutes read.

Default Virtual Behaviour in C++ vs Java

Virtual Behaviour in C++: The class member methods in C++ are, by default, non-virtual. This implies that by simply defining it, they can be turned into virtual. The virtual class can be...

3 minutes read.

Java Socket Programming

Java Socket Programming Socket programming is used for the communication between the applications, i.e., client and server running on different JRE may be connection-oriented or connectionless. The client program can be designed using the...

8 minutes read.

Java String toLowerCase() methods

Java String toLowerCase() method is used to convert all the characters of the String into lower case. Syntax: public String toLowerCase()              public String toLowerCase(Locale locale) Returns: It returns Lower...

1 minute read.

Java Program to Sort an Array of 0's, 1's, and 2’s | Dutch National Flag Problem in Java

The famed Dutch computer programmer Edsger Dijkstra's Dutch Nation Flag (DNF) challenge ranks among the most well-known programming challenges. The Dutch tricolor flag, comprising red, white, and blue, is the...

3 minutes read.

Design of JDBC

Java applications may interface using database systems from many vendors using the Java Database Connectivity (JDBC) Application Software Interface (API) from Sun Microsystem. To connect spreadsheets, JDBC and database drivers...

3 minutes read.

Access modifiers in Java

Access modifiers in Java with Example In Java, there are two types of access modifiers one is a non-access modifier, and other is access modifier. If we talk about access modifier, there...

3 minutes read.