How to Convert String to Enum Object in Java


In this example, let’s  see how to convert a string to an enum object in Java.

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