How do I use the enum type?
Author: Deron Eriksson
Description: This Java tutorial describes how to use the enum type.
Tutorial created using: Windows XP || JDK 1.6.0_10


The enum type in JavaSW can be used to conveniently represent a set of constants. Since these fields are constants, they are typically represented in uppercase letters using the Java convention for constants.

The EnumDemo class demonstrates some of the uses of the enum type. It Food enum defines four constants: HAMBURGER, FRIES, HOTDOG, and ARTICHOKE. Notice that the enum can have methods, such as the static favoriteFood method.

In the main() method, we iterate over the Food values and display each food name to the console. If the food is FRIES, we output a message, and if the food is our favorite food (ARTICHOKE), we also output a message.

After this, we iterate over a range of values in the Food enum. This range, from FRIES to ARTICHOKE, is obtained via the call to EnumSet.range() with Food.FRIES and Food.ARTICHOKE as parameters.

EnumDemo.java

package cakes;

import java.util.EnumSet;

public class EnumDemo {

	public enum Food {
		HAMBURGER, FRIES, HOTDOG, ARTICHOKE;

		public static Food favoriteFood() {
			return ARTICHOKE;
		}
	}

	public static void main(String[] args) {
		for (Food f : Food.values()) {
			System.out.println("Food: " + f);
			if (f == Food.FRIES) {
				System.out.println("I found the fries!");
			}
			if (f == Food.favoriteFood()) {
				System.out.println("I found my favorite food!");
			}
		}

		for (Food f : EnumSet.range(Food.FRIES, Food.ARTICHOKE)) {
			System.out.println("More food: " + f);
		}
	}

}

The console output for EnumDemo is shown here:

Console output from executing EnumDemo

Food: HAMBURGER
Food: FRIES
I found the fries!
Food: HOTDOG
Food: ARTICHOKE
I found my favorite food!
More food: FRIES
More food: HOTDOG
More food: ARTICHOKE

Another convenience of the enum type is that it can be used with the switch statement.