
(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).