Enumerated type (enum)

Lesson content

  • What is the enumerated type (reserved word enum)
  • Declaring and calling an enumerated type, naming convention
  • Attributes and methods in enums
  • Most common errors

What is the enumerated type (reserved word enum)

In previous lessons, simple types in Java had been explained (int, double, char, boolean), as well as the String class – all of which allow the declaration of simple attributes and cover a wide range of possible data types or values. When that’s not enough, complex types (classes) are used, and class declarations can introduce attributes, enabling an object of that class to hold multiple related values.

However, there are cases when we need to create a new data type that is not a simple type but has a strictly limited set of possible values. For example: eye color, which can only be one of four values – blue, green, brown, and violet. It could also be a list of continents (seven values): Europe, Asia, Africa, North America, South America, Australia, and Antarctica. Or transaction status: completed, canceled, or failed, etc.

It’s important to notice that using existing types like String is not suitable in these cases because it does not limit input to only allowed values. For example, if we used String for eye color and expected values like “blue”, “green”, “brown”, or “violet”, someone could enter “dog”, “tree”, or any other String value - all being invalid for eye color.

In Java, the solution for these cases is the enumerated type (or enum for short). Enums are Java classes that have a limited set of predefined values — specific instances (objects) defined at the time of declaration.

Declaring and calling an enumerated type, naming convention

An enum is declared similarly to a class, but instead of the keyword class, the reserved word enum is used. The enum name follows the same naming convention as a class (“CamelCase” with capitalized first letters of each word). The possible values (instances) of the enum are listed inside the body, separated by commas. Enum instance names follow the same convention as constants, i.e., all uppercase letters (e.g., BLUE, GREEN, LIGHT_BROWN) and words separated with underscores (_).

1 enum EnumTypeName {
2     INSTANCE_1, INSTANCE_2, ... INSTANCE_N;
3 }

The order in which instances are listed doesn’t matter. Enum values are accessed in the same way as static attributes — using the enum type name:

1 EnumTypeName.INSTANCE_1

Also note: variables of an enum type aren’t initialized using a constructor like regular class instances, but they do need to be initialized before use. Simply assign the value like this:

1 EnumTypeName variable = EnumTypeName.INSTANCE_3;

Just like with all classes and objects, the default value of an enum variable is null.

Example 1

Create an enum EyeColor with the following values:

  • BLUE, GREEN, LIGHT_BROWN, DARK_BROWN, VIOLET
1     enum EyeColor {
2         BLUE, GREEN, LIGHT_BROWN, DARK_BROWN, VIOLET;
3     }

Create a class Person with:

  • Attributes firstName and lastName
  • Attribute eyeColor, representing the person’s eye color
  • Method printInfo, which prints all data about the person
 1     class Person {
 2 
 3         String firstName;
 4 
 5         String lastName;
 6 
 7         EyeColor eyeColor;
 8 
 9         void printInfo() {
10             System.out.println(firstName + " " + lastName + 
11             ", eye color: " + eyeColor);
12         }
13     }

Create a class TestPerson which in the main method creates a new Person object named Larry Stone, with light brown eyes, and prints this person’s data to the screen.

 1 class TestPerson {
 2 
 3     public static void main(String[] args) {
 4         Person o = new Person();
 5 
 6         o.firstName = "Larry";
 7         o.lastName = "Stone";
 8 
 9         o.eyeColor = EyeColor.LIGHT_BROWN;
10 
11         o.printInfo();
12     }
13 }

This example shows that the eye color is defined by a strictly limited set of values. If any other value were assigned, Java would throw a syntax error.

Also, when the main method is run, the output for the eye color will be LIGHT_BROWN, exactly as defined in the enum.

Although enum instances behave like (static) constants in how they are defined and accessed, there is one key difference: constants always have an associated value (e.g., PI = 3.141592), while enum instances usually do not — the instance name alone is enough (e.g., eye color does not need an associated numeric or string value).

Example 2

Create an enum Continent with the following values:

  • Europe, Asia, Africa, Australia, Antarctica, South America, North America
1     enum Continent {
2         EUROPE, ASIA, AFRICA, AUSTRALIA, ANTARCTICA, 
3         SOUTH_AMERICA, NORTH_AMERICA;
4     }

Create a class Country with:

  • Attribute name
  • Attribute area (surface area in square km)
  • Attribute continent, representing the continent the country is located on
  • Method printInfo to print all country data
 1     class Country {
 2 
 3         String name;
 4 
 5         int area;
 6 
 7         Continent continent;
 8 
 9         void printInfo(){
10             System.out.println(name + ", area " + area + 
11             " km2, is on continent "+ continent);
12         }
13     }

Create a class TestCountry which in the main method creates a country named Egypt with a surface area of 1,001,450 km², located in Africa, and prints its data.

 1 class TestCountry {
 2 
 3     public static void main(String[] args) {
 4         Country d = new Country();
 5 
 6         d.name = "Egypt";
 7         d.area = 1001450;
 8         d.continent = Continent.AFRICA;
 9 
10         d.printInfo();
11     }
12 }

When the main method runs, the output will be:

1 Egypt, area 1001450 km2, is on continent AFRICA

This shows that the name of the enum instance (AFRICA) is printed exactly as defined.

Attributes and methods in enums

As mentioned, an enum is actually a special kind of Java class. In the previous examples, enums were used in their simplest form — just listing the instances. But it’s also possible to define attributes, methods, and constructors inside the enum itself. This allows each instance to have additional data and behaviors.

Example 3

Create an enum Continent2 with the following values:

  • Europe, Asia, Africa, Australia, Antarctica, South America, North America

Each continent should have a surface area (in square kilometers), stored in the attribute area:

  • Europe: 10,180,000 km²
  • Asia: 43,810,000 km²
  • Africa: 30,370,000 km²
  • Australia: 7,600,000 km²
  • Antarctica: 13,720,000 km²
  • South America: 17,840,000 km²
  • North America: 24,490,000 km²

Define a parameterized constructor to assign the surface area, and a method printInfo to print all the data about the continent.

 1 enum Continent2 {
 2 
 3     EUROPE (10180000), ASIA (43810000),
 4     AFRICA (30370000), AUSTRALIA (7600000),
 5     ANTARCTICA (13720000), SOUTH_AMERICA (17840000),
 6     NORTH_AMERICA (24490000);
 7 
 8     // The continent's surface area in square kilometers
 9     int area;
10 
11     //A constructor receiving the surface area as a parameter
12     Continent2(int area){
13         this.area = area;
14     }
15 
16     void printInfo(){
17         System.out.println(this.name() + " (area: " +
18          area + " km2)");
19     }
20 
21 }

Also create the classes Country2 and TestCountry2, similar to the previous example but using Continent2.

 1    class Country2 {
 2 
 3         String name;
 4 
 5         int area;
 6 
 7         Continent2 continent;
 8 
 9         void printInfo(){
10             System.out.print (name + ", area " + area +
11              " km2, is on continent ");
12             continent.printInfo();
13         }
14     }
 1     class TestCountry2 {
 2 
 3         public static void main(String[] args) {
 4             Country2 d = new Country2();
 5 
 6             d.name = "Egypt";
 7             d.area = 1001450;
 8             d.continent = Continent2.AFRICA;
 9 
10             d.printInfo();
11         }
12     }

This example shows that the enum Continent2 now behaves more like a regular class: it includes an attribute (area), a constructor, and a method (printInfo). Notably:

  • Enum instances are listed with specific surface areas in parentheses, which effectively calls the constructor and assigns a value.
  • The name of the enum instance (continent name) is accessed via the method name() (i.e., this.name()).

When the main method runs, the screen will display:

1 Egypt, area 1001450 km2, is on continent AFRICA (area: 30370000 km2)

Most common errors

Some common syntax errors when writing and using enums include:

  • Using the keyword class instead of enum when declaring an enum.

  • Forgetting to assign values to enum instances via the constructor — if a parameterized constructor is defined.

  • Forgetting to initialize enum-type variables before using them.

  • Using semi-columns instead of commas to separate declarations of enum instances.