Home
Map
enum ExamplesUse enums to store constants and improve compiler checking. Pass enums to methods.
Java
This page was last reviewed on Jul 19, 2023.
Enum. In Java an enum stores a list of values. Each value is given a name. We use enums, and their values, throughout a program to clarify our code.
Suppose a program uses the value 1 to mean Medium, and 2 to mean Large. We can use enum values to store these magic constants and make code more maintainable.
First example. We show an enum called Importance. The enum has 3 constants: Low, Medium and High. We create a variable of Importance type and initialize it to Medium.
Then In the if-statement, we test the values of Importance. For Low, we display 1. For Medium and High, we display 2 or 3.
if
Result It matches Importance.Medium, so the value 2 is written to the console. We use System.out.println for this function.
Console
public class Program { enum Importance { Low, Medium, High } public static void main(String[] args) { // Create an Importance variable. Importance i = Importance.Medium; // Test the Importance. if (i == Importance.Low) { System.out.println("1"); } else if (i == Importance.Medium) { System.out.println("2"); } else if (i == Importance.High) { System.out.println("3"); } } }
2
Method, switch. We pass an enum to a method: it is received by the name of the enum type, Size. And we use a switch on an enum value. We must specify only the "unqualified" constants.
Note Sometimes we use qualified constants, which include the enum type. An example of this syntax is "Size.Small."
However In a switch, we must use unqualified constants. An example of this form is "Small."
switch
public class Program { enum Size { Small, Medium, Large } static void test(Size size) { // Switch on the enum value. switch (size) { case Small: System.out.println("?"); return; case Medium: System.out.println("Is medium size"); return; case Large: System.out.println("!"); return; } } public static void main(String[] args) { // Call method and pass enum value to it. test(Size.Medium); } }
Is medium size
Qualified case error. If we try to add a qualified case label to a switch, such as Size.Small, we get an error. This is a compile-time error. We can use it to improve program quality.
Tip With unqualified enum constants in a switch, we reduce code size and make code easier to read.
The qualified case label Program.Size.Small must be replaced with the unqualified enum constant Small
Null. An enum can be null. When an enum (like Color in this program) is a field of a class, it is by default set to null. It is not initialized to a value in the enum. It has no value.
Tip We demonstrate a null-initialized static field here. A static field is just like an instance one, except it is tied to no instance.
static
public class Program { enum Color { Default, Red, Green, Blue } static Color c; public static void main(String[] args) { // An enum field is null by default. if (c == null) { System.out.println("Is null!"); } // We can assign a null enum variable to a value. c = Color.Red; System.out.println(c); } }
Is null! Red
Array, enums. As with a class, we can create an array of enums. Here, I create a three-element array of Language enums. I use the Language.Java (a good choice) enum and a "null" constant.
Array
public class Program { enum Language { Java, Python, Ruby } public static void main(String[] args) { // ... Create a three-element array. Language[] lang = new Language[3]; lang[0] = Language.Java; lang[1] = null; lang[2] = Language.Python; System.out.println(lang[0]); } }
Java
ArrayList, enums. An enum type can be used just like a class. In an ArrayList, for example, we can use the enum as the element type—and then loop over individual enums.
ArrayList
Note An enum can be used as a key type in a HashMap, but the customized EnumMap is faster for this situation.
import java.util.ArrayList; public class Program { enum Density { Low, Medium, High } public static void main(String[] args) { // Add enums to an ArrayList. ArrayList<Density> list = new ArrayList<>(); list.add(Density.Medium); list.add(Density.High); // ... Display enums. for (Density value : list) { System.out.println(value); } } }
Medium High
Name, ordinal. An enum provides the name() and ordinal() methods. The result of name() is the same as toString: it returns a string with the unqualified enum name (like "Image").
Detail This returns the enum value's index within the enum. The first entry has an ordinal of 0 and the second has an ordinal of 1.
enum DataCode { Image, Text, Combination } public class Program { static void test(DataCode code) { // Write name and ordinal of these enums. System.out.println(code.name()); System.out.println(code.ordinal()); } public static void main(String[] args) { // Call the test method. test(DataCode.Image); test(DataCode.Text); test(DataCode.Combination); } }
Image 0 Text 1 Combination 2
EnumMap. Sometimes we need to do lookups based on enum values. With an EnumMap, this operation is optimized. In constant time we can look up values based on enum keys.
EnumMap
Enums are useful throughout Java programs. They identify concepts and behaviors—such as an object's Importance. They also store magic constants, like numeric codes and values.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jul 19, 2023 (rewrite).
Home
Changes
© 2007-2024 Sam Allen.