Converting String to enum type

In many cases, we may want to convert String to enum for further processing. In the PizzaSize example, let us say we get the size of pizza as input from user. The input will be returned as String but we would like to convert to enum so that we can use it in, say switch case. Here is where, we can use the valueOf() method. Just like values() method this method is also inserted by the compiler when our enum is converted to class.

public static enum-type valueOf(String str)

package com.ibytecode.enums;

import java.util.Scanner;

public class PizzaEnumValueOf {

	enum PizzaSize {
		SMALL, MEDIUM, LARGE
	};

	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		System.out.print("Enter pizza size: ");
		String pizzaSizeStr = s.next();
		// convert String to enum - PizzaSize
		PizzaSize pizzaSize = PizzaSize.valueOf(pizzaSizeStr.toUpperCase());

		switch (pizzaSize) {
		case SMALL:
			System.out.println("Making SMALL Pizza");
			break;
		case MEDIUM:
			System.out.println("Making MEDIUM Pizza");
			break;
		case LARGE:
			System.out.println("Making LARGE Pizza");
			break;
		}
	}
}

Enter pizza size: medium
Making MEDIUM Pizza

This method throws IllegalArgumentException whenever the String cannot be converted to specified enum.

Enter pizza size: abc
Exception in thread “main” java.lang.IllegalArgumentException: No enum const class com.ibytecode.enums.PizzaEnumValueOf$PizzaSize.ABC
at java.lang.Enum.valueOf(Unknown Source)
at com.ibytecode.enums.PizzaEnumValueOf$PizzaSize.valueOf(PizzaEnumValueOf.java:1)
at com.ibytecode.enums.PizzaEnumValueOf.main(PizzaEnumValueOf.java:16)

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.