- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to convert a String to an enum in Java?
The valueOf() method of the Enum class in java accepts a String value and returns an enum constant of the specified type.
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 { //Constants with values ACTIVA125(80000), ACTIVA5G(70000), ACCESS125(75000), VESPA(90000), TVSJUPITER(75000); //Instance variable private int price; //Constructor to initialize the instance variable Vehicles(int price) { this.price = price; } //Static method to display the price public int getPrice(){ return this.price; } }
The following Java program, accepts a String value from the user, converts it into an enum constant of the type Vehicles using the valueOf() method and, displays the value (price) of the selected constant.
public class EnumerationExample { 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
- Related Articles
- How to convert an enum type variable to a string in C++?
- How to convert a JSON object to an enum using Jackson in Java?
- How to convert a String to an int in Java
- Swift: Convert enum value to String?
- How to convert a Java String to an Int?
- How to convert an array to string in java?
- How to convert a String to an InputStream object in Java?\n
- How to enumerate an enum with String type?
- Convert an ArrayList of String to a String array in Java
- How to convert/read an input stream into a string in java?
- How to convert a comma separated String into an ArrayList in Java?
- How to convert/store a string of numbers in to an array in java?
- How to convert comma seperated java string to an array.
- Write a program to convert an array to String in Java?
- How to call another enum value in an enum's constructor using java?

Advertisements