ADVERTISEMENT
ADVERTISEMENT

Java program to convert the string into an enum constant

Java example to convert the string into an enum constant.
Submitted by Nidhi, on April 04, 2022

Problem Solution:

In this program, we will convert a string variable into an "enum" constant using the valueOf() method and print the result.

Program/Source Code:

The source code to convert the string into an enum constant is given below. The given program is compiled and executed successfully.

// Java program to convert the string 
// into an enum constant

public class Main {
  enum Vehicle {
    BIKE,
    CAR,
    BUS
  }

  public static void main(String[] args) {
    String str = "BUS";

    Vehicle v = Vehicle.valueOf(str);

    System.out.println(str);
  }
}

Output:

BUS

Explanation:

In the above program, we created an enumeration Vehicle inside class Main. The enum Vehicle contains 3 constants BIKE, CAR, BUS. The Main class also contains a static method main(). The main() method is the entry point for the program, here we created a string variable initialized with "BUS". Then we converted the string into an enum constant using the valueOf() method and printed the result.

Java Enums Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.