How to Create an Enum Type in Java

Java’s boolean type is very handy, but sometimes you need more values. After all, a traffic light’s values can be green, yellow, or red. A playing card’s suit can be spade, club, heart, or diamond. And a weekday can be Monday, Tuesday, Wednesday, Thursday, or Friday.

Life is filled with small sets of possibilities, and Java has a feature that can reflect these possibilities. The feature is called an enum type. It’s available from Java version 5.0 onward.

Consider the results of a baseball game. The game has three possible endings — the Hankees win, the Socks win, or the game is tied. You can represent the possibilities with the following line of Java code:

enum WhoWins {home, visitor, neither}

This week’s game is played at Hankeeville’s SnitSoft Stadium, so the value home represents a win for the Hankees, and the value visitor represents a win for the Socks.

One of the goals in computer programming is for each program’s structure to mirror whatever problem the program solves. When a program reminds you of its underlying problem, the program is easy to understand and inexpensive to maintain.

For example, a program to tabulate customer accounts should use names like customer and account. And a program that deals with three possible outcomes (home wins, visitor wins, and tie) should have a variable with three possible values. The line enum WhoWins {home, visitor, neither} creates a type to store three values.

The WhoWins type is called an enum type. Think of the new WhoWins type as a boolean on steroids. Instead of two values (true and false), the WhoWins type has three values (home, visitor, and neither). You can create a variable of type WhoWins

WhoWins who;

and then assign a value to the new variable.

who = WhoWins.home;

Dummies Insider

Sign up for insider news on books, authors, discounts and more content created just for you.