Java – Convert String to Enum object

In Java, you can use Enum valueOf() to convert a String to an Enum object, review the following case study :

1. Java Enum example

WhoisRIR.java

package com.mkyong.whois.utils;

public enum WhoisRIR {
    ARIN("whois.arin.net"),
    RIPE("whois.ripe.net"),
    APNIC("whois.apnic.net"),
    AFRINIC("whois.afrinic.net"),
    LACNIC("whois.lacnic.net"),
    JPNIC("whois.nic.ad.jp"),
    KRNIC("whois.nic.or.kr"),
    CNNIC("ipwhois.cnnic.cn"),
    UNKNOWN("");

    private String url;

    WhoisRIR(String url) {
        this.url = url;
    }

    public String url() {
        return url;
    }
}

2. Problem

Given a String “arin”, how to convert it back to the above Enum object?

TestEnum.java

package com.mkyong.whois.utils;

public class TestEnum {

	public static void main(String[] args) {
	
		//How to convert this?
		WhoisRIR rir = "arin";
		
	}

}

3. Solution

To solve it, you can use enum valueOf() function and convert a String to an Enum object.

TestEnum.java

package com.mkyong.whois.utils;

import java.util.Locale;

public class Test {

    public static void main(String[] args) {

        // Solution : Uses valueOf()
        System.out.println(WhoisRIR.valueOf("arin".toUpperCase()));

        // Recommended Solution : add locale
        WhoisRIR rir = WhoisRIR.valueOf("ripe".toUpperCase(Locale.ENGLISH));
        System.out.println(rir);
        System.out.println(rir.url());

		// Error, no enum constant, case sensitive
		//System.out.println(WhoisRIR.valueOf("arin"));

    }

}

Output

ARIN
RIPE
whois.ripe.net

References

  1. Oracle – JDK 7 Enum JavaDoc
  2. Oracle : String toUpperCase JavaDoc
  3. Oracle Doc – Enum Types
author image

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities. Read all published posts by

Comments

avatar
3000