Using Java Enums
See Java enums in action and learn their best practices
Join the DZone community and get the full member experience.
Join For FreeIn applications, you often need to work with a set of constant values. For example, representing a contract status with the “permanent”, “temp”, and “intern” values, or directions with the “north”, “south”, “east”, and “west” values.
In Java, you use the enum type (short for enumeration), a special datatype introduced in Java 5 to represent such lists of predefined constants.
In this article, I’ll discuss how to define and use enum types. I’ll also include example code along with JUnit test cases. If you are new to JUnit, I suggest going through my JUnit series of posts.
Defining Java Enums
You can define an enum type either independently outside of any class or as part of a class. The code to define an enum independently is:
package springframework.guru.enumexample;
enum Days{
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}
The preceding code defines an enum type, Days. The names of the enum type’s fields are in uppercase letters, as they are constants.
Here is the JUnit test code.
package springframework.guru.enumexample;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class SimpleEnumExampleTest {
@Test
public void simpleEnumExampleOutsideClassTest(){
Days day = Days.SUNDAY;
System.out.println("Days enum is set a value: "+day);
assertEquals(Days.valueOf("SUNDAY"), day);
}
}
The test code assigns a value to the day variable of the enum type, Days. The day variable can take any of the seven defined values. In this case, it is set to SUNDAY. The test code then asserts the value.
The output of running the test in IntelliJ is: