Enums in Java

Slide-together : now with cards on Flickr
(Photo: Slide-together : now with cards by fdecomite)

Enums are highly useful data types introduced in Java SE 5.0.  Though I love using them I often forget the exact syntax so this post is to remind me later how to use it.

public enum Example {
  FOO,BAR
}

// create one using its name
Example myExample = Example.valueOf(“bar”.toUpperCase());

// if statement
if (myExample == Example.FOO) System.out.println(“FOO!”);

// switch statement
switch (myExample) {
  case FOO: System.out.println(“FOO!”);
  case BAR: System.out.println(“BAR!”);
}

// output as String using name
System.out.println(myExample.name());

For further reading please see Java’s Enums guide and Enum Types (The Java™ Tutorials > Learning the Java Language > Classes and Objects).