betweenGo

Enums in Java

by Frank Kim on Sep.02, 2009, under Java SE

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


  • Share/Bookmark

Related posts:

  1. Covariant Return Types in Java
  2. Java allocation is no longer expensive
  3. Printing out an array
  4. Playing with Dates in Java
  5. Cygwin Bash Scripts and Java

:,

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!