Enumerations. Keyword enum. Examples
Contents
- 1. The concept of enumeration. The general form of an enumeration declaration. The enum keyword
- 2. Examples of programs that use enumerations
- 3. Method values(). Get enum constants as an array
- 4. Method valueOf(). Convert string representation of a constant to a value from an enumeration
- Related topics
Search other resources:
1. The concept of enumeration. The general form of an enumeration declaration. The enum keyword
Enumerations have appeared in Java since JDK 5. In the most general case, enumerations are a list of named constants. The enum keyword is used to declare an enumeration. Working with enumerations in Java has its own peculiarities that are not typical for some other programming languages, in particular C++. In the Java language, enums are classes. Therefore, they have all the capabilities of classes. This means that enumerations can have constructors, methods, instance variables, and interface implementations.
The general form of declaring an enumeration is as follows:
enum EnumName { constant1, constant2, ..., constantN }
here
- EnumName is the name of the enumeration, which is the data type. EnumName is also the name of the class;
- constant1, constant2, …, constantN – a list of named constants constituting a set of values of the EnumName enumeration. Named constants are public static final members of the EnumName class. These constants are also called self-typed.
Based on the calculation type of EnumName, you can declare variables of this type according to the following pattern
EnumName obj;
Here obj – the name of an instance of type EnumName. An instance of the enumeration type obj is created without using the new operator. This means that a variable of an enumeration type is declared and used in the same way as a variable of any primitive type (int, float, char, …).
The obj variable can receive values from many constants declared in the EnumName enumeration, for example
obj = EnumName.constant1;
In Java, an enumeration can operate on constants of floating point types (float, double).
⇑
2. Examples of programs that use enumerations
2.1. Declaring and using the simplest enumeration. Determining the name of the month of the year
Task. Declare an enumeration Months containing a list of constants corresponding to the abbreviated name of the month of the year. In the demo program, provide input of the month number (1..12) and output of the corresponding constant from the enumeration instance.
Solution.
To enter the month number from the keyboard, the program uses the capabilities of the Scanner class.
The listing of a program that solves this problem is as follows
import java.util.Scanner; // An enumeration containing constants associated with the months of the year enum Months { Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec } public class TrainEnumerations { public static void main(String[] args) { // Enumeration // 1. Declare a variable of type Months Months mn = Months.Jan; // 2. Enter the month number from the keyboard System.out.print("month = "); Scanner input = new Scanner(System.in); int numMonth = input.nextInt(); // 3. By the month number, assign the corresponding value to the instance mn switch (numMonth) { case 1: mn = Months.Jan; break; case 2: mn = Months.Feb; break; case 3: mn = Months.Mar; break; case 4: mn = Months.Apr; break; case 5: mn = Months.May; break; case 6: mn = Months.Jun; break; case 7: mn = Months.Jul; break; case 8: mn = Months.Aug; break; case 9: mn = Months.Sep; break; case 10: mn = Months.Oct; break; case 11: mn = Months.Nov; break; case 12: mn = Months.Dec; break; default: System.out.println("Incorrect input"); return; } // Print the name of the constant corresponding to the entered month number System.out.println(mn); } }
Test example
month = 8 Aug
⇑
2.2. Using an enumeration name in a switch statement
This example demonstrates the use of an enumeration instance to control a switch statement.
Task.
The Seasons enumeration is specified, which describes the four seasons. Implement input from the keyboard of the season number (1..4). Calculate the length of the season in days from the season number. Consider that the year is not a leap year.
Solution.
import java.util.Scanner; // An enumeration that describes the seasons enum Seasons { Spring, Summer, Autumn, Winter } public class TrainEnumerations { public static void main(String[] args) { // Using an enum in a switch statement // 1. Declare an instance of the Seasons type Seasons season; // 2. Enter the number of the seasons System.out.print("Season (1..4) = "); Scanner inStr = new Scanner(System.in); int numSeason = inStr.nextInt(); // 3. Get the value of a constant based on the season number switch (numSeason) { case 1: season = Seasons.Spring; break; case 2: season = Seasons.Summer; break; case 3: season = Seasons.Autumn; break; case 4: season = Seasons.Winter; break; default: System.out.println("Incorrect input."); return; } // 4. Calculate the number of days in a season based on season. // Use the switch statement. System.out.println("season = " + season); int nDays = 0; switch (season) { case Spring: nDays = 92; break; case Summer: nDays = 92; break; case Autumn: nDays = 91; break; case Winter: nDays = 90; break; } // 5. Display the result System.out.println("Number of days = " + nDays); } }
Test example
Season (1..4) = 2 season = Summer Number of days = 92
⇑
3. Method values(). Get enum constants as an array
The values() method allows you to convert a list of named constants from the enumeration to array. The general form of the method is as follows
public static enum_type [] values()
here enum_type is the type of the enumeration whose constants are to be converted to the array.
Example.
The example uses the values() function to form an array of constant values from the Days enumeration that describes the days of the week.
import java.util.Scanner; // Enumeration. // List of days of the week enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat } public class TrainEnumerations { public static void main(String[] args) { // Method values() // 1. Get the value of constants as an array Days arrayDays[] = Days.values(); // 2. Display elements of array arrayDays for (int i=0; i<arrayDays.length; i++) { System.out.println(arrayDays[i]); } } }
The result of the program
Sun Mon Tue Wed Thu Fri Sat
⇑
4. Method valueOf(). Convert string representation of a constant to a value from an enumeration
The valueOf() method allows you to get an enumerated representation of a constant as a string. The general form of the method is as follows
public static enum_type valueOf(String str)
here
- enum_type – the type of enumeration;
- str – a string representation of a constant from the enum_type enumeration.
Example.
The example demonstrates how to use the valueOf() method to get the constant value from the Days enumeration.
import java.util.Scanner; // Enumeration. // List of days of the week enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat } public class TrainEnumerations { public static void main(String[] args) { // Method valueOf() // Enter a string for the name of the day System.out.print("Day = "); Scanner inStr = new Scanner(System.in); String strDay = inStr.next(); // line with the name of the day // Get the value of a constant Days day; day = Days.valueOf(strDay); // Enter the resulting constant value from the day enumeration System.out.println(day); } }
Test example
Day = Fri Fri
⇑
Related topics
- Using enums as classes. Examples of declaring enumerations containing constructors, internal fields, methods
- Class Enum. Methods: clone(), compareTo(), getDeclaringClass(), hashCode(), name(), ordinal(), toString()
⇑