In Java, an enum (short for enumeration) is a special data type that defines a fixed set of named constants. It is a standard, language-defined feature (not slang or informal) introduced in Java 5.0 (J2SE 5.0) via JSR 201. The word comes from the Latin enumerare, meaning “to count out” or “to list one by one.” In Java, an enum is declared using the enum keyword, and it is a full-fledged class that can have fields, methods, and constructors, but its instances are limited to the constants you define. For example:
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
This defines a type Day with seven possible values. Unlike a simple int constant, an enum provides type safety, meaning you cannot accidentally assign a value outside the defined set.
Background and Evolution
Before Java 5, developers used int constants or String constants to represent fixed sets of values, like:
public static final int MONDAY = 0;
public static final int TUESDAY = 1;
This approach was error-prone because any integer could be passed where a day was expected, and there was no compile-time checking. The Typesafe Enum pattern (a class with private constructors and public static final instances) was a common workaround, but it was verbose. Java 5 formalized this pattern into the enum keyword, making it a first-class language feature. The design was influenced by similar constructs in C and C++, but Java’s enums are more powerful because they are classes.
How Enum Works in Java
When you declare an enum, the compiler creates a class that extends java.lang.Enum (which is an abstract class). Each constant is an instance of that enum class. For example, Day.MONDAY is an object of type Day. Enums can have:
- Fields and methods: You can add instance variables and methods to an enum.
- Constructors: Enum constructors are private by default and are called only when the constants are created.
- Abstract methods: Each constant can override an abstract method to provide different behavior.
- Interfaces: An enum can implement interfaces.
Here is a richer example:
enum Planet {
MERCURY(3.303e+23, 2.4397e6),
VENUS(4.869e+24, 6.0518e6),
EARTH(5.976e+24, 6.37814e6);
private final double mass; // in kilograms
private final double radius; // in meters
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
public double surfaceGravity() {
double G = 6.67300E-11;
return G * mass / (radius * radius);
}
}
Every enum implicitly has static methods values() (returns an array of all constants) and valueOf(String) (returns the constant with that name), as well as an ordinal() method that gives the position (starting at 0). The name() method returns the constant’s name as a String.
How to Choose Between Enum and Alternatives
Use an enum when you have a fixed, known set of constants that are logically related. Common examples: days of the week, months, colors, states (e.g., ORDER_STATUS), or configuration keys. Alternatives include:
- int/String constants: Simpler but less safe and less readable. Avoid for new code.
- Set of constants: If you need to combine multiple values (e.g., permissions), use
EnumSetorEnumMap. - Class with static final instances: This is the pre-Java 5 pattern; enums are the modern replacement.
- Database lookup tables: If the set can change at runtime (e.g., user-defined categories), do not use an enum; use a database table and a regular class.
In short, if the set is truly fixed at compile time and you want type safety, an enum is the best choice.
Common Problems and Misconceptions
One common misconception is that enums are just named integers. In Java, they are objects, so you cannot compare them with ==? Actually, you can use == because each constant is a singleton, and == checks reference equality, which works for enums. However, using equals() is also fine. Another issue is relying on ordinal() for logic; if you reorder constants, the ordinal changes, breaking your code. Instead, store an explicit field for a stable ID. Also, enums are not extensible; you cannot add a constant to an existing enum at runtime. If you need that, use a different approach.
Another pitfall: using enums in switch statements is straightforward, but remember that each enum constant is an object, so you cannot use them in a switch without the enum type being known. Also, enums are serializable by default, but if you add fields, ensure they are serializable or mark them transient.
Comparisons: Enum vs. Other Languages
Java enums are more powerful than enums in C or C++. In C, an enum is just a set of integer constants with no type safety. In C++, enum class (C++11) provides type safety, but still lacks methods. Java enums are full classes, so you can add behavior. In Python, enums (via the enum module) are similar but with different syntax. In JavaScript, there is no native enum; developers often use objects or frozen arrays. Java’s enums are a model of type-safe constants.
Best Practices and Performance
Enums are compiled into regular classes, so they have a small memory overhead compared to ints, but for most applications it is negligible. Use enums to improve code readability and maintainability. Best practices include:
- Use
EnumSetandEnumMapfor efficient collections of enum constants. - Implement interfaces to give enums common behavior.
- Use the
switchstatement with enums instead of if-else chains. - Override
toString()to return a user-friendly name if the constant name is not suitable. - If you need to associate data with each constant, use a constructor and fields, as shown above.
Performance-wise, enums are as fast as regular objects; the JVM optimizes common patterns. There is no significant cost to using enums over ints in most scenarios.
Frequently Asked Questions
Can I add new constants to an enum at runtime? No. Enums are fixed at compile time. If you need a dynamic set, use a regular class with a collection.
Is it safe to compare enums with ==? Yes, because each constant is a singleton, so reference equality works. Use == for performance, but equals() is also fine.
Can an enum have a constructor? Yes, but it must be private (or package-private). You cannot call it from outside the enum.
What is the difference between name() and toString()? By default, name() returns the exact constant name (e.g., MONDAY), while toString() also returns the name unless you override it. You can override toString() to return a more readable string.
Can enums be used in a switch statement? Yes, and it is a common use case. The switch case labels must be the unqualified constant names.
Are enums thread-safe? Yes, because they are immutable once the class is loaded. The JVM ensures safe publication.
Conclusion
In summary, an enum in Java is a type-safe, object-oriented way to define a fixed set of constants. It is a standard language feature, not slang, and it originated from the need to replace error-prone integer constants. By using enums, you get compile-time checking, built-in methods, and the ability to attach behavior. For any fixed set of related constants, enums are the recommended choice in modern Java.
Related
- Excel Undo Encrypt with Password? How to Remove It
- Excel Truck Group Jobs: Pay, Hiring & Reviews
- Excel Track Purdue Global: What It Is & How It Works
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Custom Cover Page in Word: Create and Add Your OwnTo add a custom cover page in Word, place a new page at the start of your document,…
- How to Delete Blank Rows in an Excel Column SafelyTo delete entire rows where a chosen Excel column is blank, select the data range, choose Home >…
- Excel Solver Limitations: What It Can and Cannot DoExcel Solver is best suited to small, well-structured optimization models: the standard Solver add-in can adjust at most…
- Excel Conditional Formatting for Values Less Than a CellTo highlight Excel values that are less than a value in another cell, select the cells to format,…
- How to Open a Numbers File in Excel on a PCTo open a Numbers spreadsheet in Excel on a Windows PC, first convert the Apple .numbers file to…
- Excel Not Responding: Should You Wait or Force Quit?If Excel says Not Responding, wait briefly if the workbook may be calculating, refreshing data, or saving; do…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.