Skip to main content

Java Enum

Java's enum not only includes names but can also have fields like other classes.

Define Enum

Only have names:

public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}

Fields:

public enum InstanceType {
TINY("t2.nano", 1, 0.5),
MEDUIM("t2.medium", 2, 4),
LARGE("t2.large", 2, 8); // NOTE: it is semicolon, not comma

private final String spec;
private final int vcpu;
private final double memory;
}

Enum cannot extend other class because it is already inheriting from java.lang.Enum. But Enum can implement interface.

Get all enum values

Java Enum has builtin in values() method (generated at compile time) to get all enum values. Other languages like go requires handwritten code or external generator.

for(InstanceType type : InstanceType.values()) {
System.out.println(type);
}

Parse enum from string

During compile time a valueOf method is generated, but it requires the string to be exact same as enum name. If you defined enum Color { RED, GREEN }, then Color.valueOf("RED") will work but Color.valueOf("red") will throw IllegalArgumentException

java.lang.IllegalArgumentException: No enum constant dev.at15.javadocs.EnumTest.Color.Red

References