Convert enum to String and Enums with static fields


Convert enum to String

Sometimes you want to convert your enum to a String, there are two ways to do that.

Assume we have:

public enum Fruit {
   APPLE, ORANGE, STRAWBERRY, BANANA, LEMON, GRAPE_FRUIT;
}

So how do we convert something like Fruit.APPLE to "APPLE"?

Convert using name()

name() is an internal method in enum that returns the String representation of the enum, the return String represents exactly how the enum value was defined.

For example:

System.out.println(Fruit.BANANA.name()); // "BANANA"
System.out.println(Fruit.GRAPE_FRUIT.name()); // "GRAPE_FRUIT"

Convert using toString()

toString() is, by default, overridden to have the same behavior as name()

However, toString() is likely overridden by developers to make it print a more user friendly String

  • Don't use toString() if you want to do checking in your code, name() is much more stable for that. Only use toString() when you are going to output the value to logs or stdout or something

By default:

System.out.println(Fruit.BANANA.toString()); // "BANANA"
System.out.println(Fruit.GRAPE_FRUIT.toString()); // "GRAPE_FRUIT"

Example of being overridden

System.out.println(Fruit.BANANA.toString()); // "Banana"
System.out.println(Fruit.GRAPE_FRUIT.toString()); // "Grape Fruit"

Enums with static fields

If your enum class is required to have static fields, keep in mind they are created after the enum values themselves. That means, the following code will result in a NullPointerException:

enum Example {
	ONE(1), TWO(2);
 
	static Map<String, Integer> integers = new HashMap<>();
 
	private Example(int value) {
		integers.put(this.name(), value);
	}
}

A possible way to fix this:

enum Example {
 
	ONE(1), TWO(2);
 
	static Map<String, Integer> integers;
 
	private Example(int value) {
		putValue(this.name(), value);
	}
 
	private static void putValue(String name, int value) {
		if (integers == null)
			integers = new HashMap<>();
		integers.put(name, value);
	}
}

Do not initialize the static field:

enum Example {
 
	ONE(1), TWO(2);
 
	// after initialisisation integers is null!!
	static Map<String, Integer> integers = null;
 
	private Example(int value) {
		putValue(this.name(), value);
	}
 
	private static void putValue(String name, int value) {
		if (integers == null)
			integers = new HashMap<>();
		integers.put(name, value);
	}
 
	// !!this may lead to null poiner exception!!
	public int getValue(){
		return (Example.integers.get(this.name()));
	}
}

initialisisation:

  • create the enum values
    • as side effect putValue() called that initializes integers
  • the static values are set
    • integers = null; // is executed after the enums so the content of integers is lost

Basic Programs