An enum in Java is a special class that represents a fixed set of constants, like days of the week, menu options, or HTTP status codes. Defining an enum is straightforward: use the enum keyword followed by the name and a comma-separated list of constants. For example, enum Color { RED, GREEN, BLUE }. This guide walks you through the basics, adding fields and methods, and common pitfalls.
What You’ll Need
- Java Development Kit (JDK) 8 or later (enums have been in Java since 1.5, so any modern JDK works).
- A text editor or an IDE like IntelliJ IDEA, Eclipse, or VS Code.
- Basic familiarity with Java syntax, classes, and methods.
Step-by-Step
- Create a Java file. Name it the same as the enum you plan to define. For example, if your enum is
Day, save the file asDay.java. If the enum is a nested type inside a class, it can be defined inside that class’s braces. - Declare the enum. Use the
enumkeyword, followed by the enum name (conventionally PascalCase). Then add a pair of curly braces. Inside, list the constants, separated by commas. End with a semicolon if you add anything after the constants (fields, methods, constructors).public enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY } - Use the enum. In another class, reference the enum type and assign a constant:
Day today = Day.MONDAY; System.out.println(today); // prints MONDAY - Add fields and a constructor (optional). Enums can have data and behavior. Declare private final fields, a constructor that takes arguments, and getter methods. The constants must call the constructor with the appropriate values.
public 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 mass() { return mass; } public double radius() { return radius; } } - Add methods (optional). You can define instance methods, and even abstract methods that each constant overrides. For example, to give each day a “isWeekend” method:
public enum Day { MONDAY(false), TUESDAY(false), WEDNESDAY(false), THURSDAY(false), FRIDAY(false), SATURDAY(true), SUNDAY(true); private final boolean weekend; Day(boolean weekend) { this.weekend = weekend; } public boolean isWeekend() { return weekend; } } - Use enums in switch statements. Enums work perfectly with
switch. Note that in a switch on an enum, you use the constant name without the enum prefix.switch (day) { case MONDAY: System.out.println("Start of work week"); break; case SATURDAY: case SUNDAY: System.out.println("Weekend!"); break; default: System.out.println("Midweek"); } - Iterate over enum values. Use the built-in
values()method to get an array of all constants.for (Day d : Day.values()) { System.out.println(d + " is weekend? " + d.isWeekend()); } - Look up an enum from a string. Use
valueOf(String)to get the constant whose name matches exactly (case-sensitive). It throwsIllegalArgumentExceptionif not found.Day d = Day.valueOf("MONDAY"); // works // Day d2 = Day.valueOf("monday"); // throws IllegalArgumentException
Common Mistakes
- Forgetting the semicolon after the constant list. If you add fields or methods, you must put a semicolon after the last constant. Without it, the compiler thinks the next token is another constant.
- Using
newto instantiate an enum. Enums cannot be instantiated withnew. The constants are the only instances. Attemptingnew Day()is a compile error. - Comparing enums with
==vsequals(). Both work because each constant is a singleton, but==is safe and recommended. Avoid usingequals()with null;==handles null gracefully. - Mutable fields. Enums are meant to be immutable. If you declare fields without
final, you risk changing the state of a constant, which can lead to bugs. Make fieldsprivate final. - Defining an enum inside a method. Local enums are not allowed in Java. Enums must be top-level or nested inside a class (static nested).
Tips
- Use enums instead of integer constants (like
public static final int STATUS_OK = 200;) because enums provide type safety and readability. - Override
toString()to return a user-friendly label if the constant name is not display-friendly (e.g.,MONDAYcould display as “Monday”). - Use
EnumSetandEnumMapfor efficient collections of enum values. - If you need to associate multiple values with a constant, consider adding a constructor with multiple parameters.
- Remember that enums implicitly extend
java.lang.Enum, so they cannot extend another class. They can implement interfaces.
Troubleshooting
Compile error: “enum” is a keyword. Make sure you are using the lowercase enum, not Enum (which is a class name).
Compile error: “expected” or “illegal start of expression”. Check for a missing semicolon after the constant list if you added fields or methods. Also check that the enum is not inside a method.
Runtime error: IllegalArgumentException when using valueOf(). The string must match the constant name exactly, including case. Use values() to iterate and compare if you need case-insensitive lookup.
Enum constants not visible in another class. Ensure the enum is declared public (if top-level) and that you import it if it’s in a different package.
Cannot switch on enum in older Java versions. Switch on enums has been supported since Java 5. If you are using a very old compiler, upgrade to at least Java 5.
Frequently Asked Questions
- Can an enum have abstract methods? Yes, you can declare an abstract method in the enum and provide a concrete implementation for each constant. Each constant must override the method.
- Can I create an enum with duplicate constants? No, each constant name must be unique. The compiler will complain if you try to declare two constants with the same name.
- How do I get the index of an enum constant? Use the
ordinal()method, which returns the zero-based position. However, avoid relying on ordinal for logic because it changes if you reorder constants. - Can enums be serialized? Yes, enums are serializable by default. The serialized form is the constant name, and deserialization returns the existing singleton instance.
- Can I compare enums with
equals()? Yes, but==is more efficient and safe. Both work because each constant is a singleton. - Can an enum implement an interface? Yes, an enum can implement one or more interfaces, just like a regular class. You can then override the interface methods.
Related
- Traffic Signs in Kansas: Rules, Colors, and Meanings
- Federal Reserve Balance Sheet Explained
- How to Split a String in PySpark (with Examples)
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Insert a Checkbox in Excel on Windows 7: Step-by-StepTo insert a checkbox in Excel on Windows 7, use the Form Controls option: enable the Developer tab,…
- Excel Web Consolidate: What Works and What Doesn’tExcel for the web does not include the desktop Excel Data > Consolidate command. To combine data in…
- Alternating Color Rows in Excel: 2 Easy MethodsTo add alternating color rows in Excel, select your data and choose Insert > Table, then pick a…
- Excell Battery P/N 2EXL7431-001: What It MeansExcell battery part number 2EXL7431-001 cannot be reliably matched to a particular device or replacement battery from the…
- Excel Edit History: How to View Changes and VersionsTo find recent cell edits in Microsoft Excel for Microsoft 365 on Windows, open the workbook saved in…
- Split Cell Colour in Excel: Methods and LimitationsExcel cannot split one cell into two independently coloured halves using a built-in cell-fill setting. To show two…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.