Converting String to enum type

14 February 2012 By Nithya Vasudevan 2,894 views No Comment
0 Flares Twitter 0 Facebook 0 Google+ 0 0 Flares ×

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 {

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

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

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(
at com.ibytecode.enums.PizzaEnumValueOf.main(

Tags: , , , , , ,