×

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

Empty Statement in Java

The three sorts of statements in Java are control, expression, and declaration statements. Additionally, another statement is referred to as an empty statement. In this section, we will discuss about...

4 minutes read.

Java Constant

A constant is an unchangeable entity in coding, as its title implies. The value which cannot be altered, in other terms. We shall understand about Java constants and exactly how...

3 minutes read.

How to sort an array in Java

Sorting is the process of arranging the elements of a list or array in a specific order, either ascending or descending. The sorting criterion numerical and alphabetical is commonly used...

6 minutes read.

Automatic Resource Management

In computer programming, resource management refers to the wide set of techniques for the effective management of the system resources. There are two ways of management of resources: The computer program itself...

2 minutes read.

Java Trim

Leading and leaving spaces are removed by the built-in Java String trim() method. Space seems to have the Unicode element of "x0040." Java trim() function looks for all of these...

3 minutes read.

Shift right zero Fill Operator in Java and Operator Shifting

Left shift operator ( << ) : The left shift operator is an operator which performs its action at the bits level of a binary Operator. That means when you perform...

4 minutes read.

Iccanobif Numbers in Java

In this article, you will be very well equipped with the knowledge of iccanobif numbers in Java. You will also know how they are formed and basic example programs on...

3 minutes read.

Sleep Time in Java

Sleep is amethod in java that is related to thread class and it is a concept of multithreading and is used to stop the execution of the current thread a...

4 minutes read.

Java Xmx

This section will explain what Xmx in Java is and how to establish a Java application's maximum heap size. When we execute a Java application, it occasionally displays an error message...

3 minutes read.

Undo and Redo Operations in Java

Undo and redo operation are the most widely used operation while dealing with file. In this section, we will discuss how to implement undo and redo operation in Java. Undo Redo...

2 minutes read.

Differences between Set and List in Java

Set in Java: The Java. util package contains an interface called the set. The set interface expands the Collection interface. A collection interface is an unordered collection of List where duplicates...

6 minutes read.

Java Class Syntax

A class is a fundamental building piece in object-oriented programming. It can be characterised as a template that outlines the information and actions connected to the creation of a class....

3 minutes read.

New Features of Java 14

 Features like Switch expressions and text blocks which are previewed in Java 13 version are standardized in Java 14. Features in Java 14 Switch ExpressionText BlocksRecordsNull Pointer ExceptionsInstance ofPackaging ToolGarbage collectors 1.Switch Expressions Switch...

3 minutes read.

Replace character in string Java

Characters in Java In the package of Java language, there is a container class called Character. A single field of type char is contained in a Character object. For manipulating characters,...

4 minutes read.

Java Null Keyword

Null is a term that is only used for literal values in Java. Although it appears to be a term, it is a literal opposite of true and false. Java's...

3 minutes read.

Perfect Number in Java

The concept of a perfect number in Java will be defined in this chapter, along with creating Program code that determine whether a specific number is perfect or not. Additionally,...

4 minutes read.

Selection Sort in Java

Selection Sort in Java Selection sort is also a simple sorting algorithm that works by repeatedly finding the minimum element from the unsorted portion of the input array, and placing it...

5 minutes read.

Java Lambda foreach

Before understanding lamda foreach, one must know about foreach loop in Java. foreach loop in Java Since J2SE 5.0, there has been a for-each loop in Java, also known as an extended...

4 minutes read.

How to check Date Null in Java?

In this section, we will be acknowledged about Date Null in Java. The date null in Java is an entity that is used when there is no specified value for...

3 minutes read.

Java Try Resource

In Java, a try argument that specifies one or more resources is known as a try-with-resources statement. When your program is finished utilizing an object, it must be closed, which...

4 minutes read.