Java Tutorials – Lesson 7: Enumerated Types (enums)

Google+ Pinterest LinkedIn Tumblr +

Enumerations (enums) are used to represent static values such as colors, states, and much more. Lets begin with a code example.

Code Example:

enum OperatingSystem { Windows, Unix, Solaris, Mac }; //This defines the enum

OperatingSystem myOS = OperatingSystem.Windows; //creating an enum type variable and initializing

“OperatingSystem” is the name of the enum type, and it has 4 possible states(each operating system). Each state is given an integer value. By default, this starts at 0.

  • OperatingSystem.Windows=0
  • OperatingSystem.Unix =1
  • and so on…

You can explicitly give each state its own value, but each value must be a unique integer.

Code Example:

enum CardSuit { Spade = 3, Heart = 25; Club = 5; Diamond =2};

Although this example does not make sense to define such random numbers, there are cases where you may want to explicitly give enum values.

Code Example:

enum Month { January=1, February, March, April, May, June, July, August, September, October, November, December };

In this example, January is assigned 1 to be consistent with convention. This means the following months will be given increasing integer values, 2 for February, 3 for March etc…

As you can see enums are fairly useful in representing different states or attributes. They allow you to give a text description of an integer value so you do not have to remember which number you used to represent the card suit Diamond, for example.

Using enums With Switch…Case Statements

As you recall from the switch…case lesson, enumerated types can also be used.

Code Example:

enum OperatingSystem { Windows, Unix, Solaris, Mac };

OperatingSystem myOS= OperatingSystem.Unix;



case(OperatingSystem.Windows): System.out.println(“my OS is Windows”);


case(OperatingSystem.Unix); System.out.println(“my OS is Unix”);




About Author

Leave A Reply