Java Enumeration Primer

Here is a quick primer on Java enums:

  • Enumeration is fixed set of constants
  • Provides type-safe representation of constant data
  • enum is the Java class that represents enumeration
  • enum cannot extend any other class
  • Constants in enum are public,final, and static
  • enum can declare additional methods and fields
  • enum can declare any number of constructors
  • values() returns array of enum values
  • If you need int value, you can use ordinal() static method
  • static valueOf() method can be used to convert a string into corresponding enum
  • enum can be used in switch statement

Here is an example of enum with constructors:


public enum IceCream {

	PLAIN(2),
	SUGAR(3),
	WAFFLE(5);

	private IceCream(int scoops) {
		this.scoops = scoops;
	}

	public final int scoops;
}

public class TestEnum {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		IceCream cone1 = IceCream.PLAIN;
		IceCream cone2 = IceCream.SUGAR;
		IceCream cone3 = IceCream.WAFFLE;

		System.out.println("cone 1 needs " + cone1.scoops + " scoops");
		System.out.println("cone 2 needs " + cone2.scoops + " scoops");
		System.out.println("cone 3 needs " + cone3.scoops + " scoops");

	}

}

Output:

cone 1 needs 2 scoops
cone 2 needs 3 scoops
cone 3 needs 5 scoops

One thought on “Java Enumeration Primer

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>