How to Convert String to Enum Type in java


In this example, let’s us see to convert String to Enum object in Java.

Source Code

package com.beginner.examples;

public class ConvertStringtoEnum {
	
	public enum Weather {
	    winter,
	    spring,
	    summer,
	    fall
	}

	public static void main(String[] args) {
		
		//Enumeration Conversion String
		String win = Weather.winter.toString();
        String win2 = Weather.winter.name();
        System.out.println(win);
        System.out.println(win2);
        
        //String Conversion Enumeration
        Weather weather = Weather.valueOf("spring");
        System.out.println("------");
        System.out.println(weather);
	}
	
}

Output:

winter
winter
------
spring
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments