An enum (short for enumeration) in Java is a special data type that lets you define a fixed set of named constants. For example, days of the week, card suits, or order statuses. Enums are more than just a list of constants—they can have fields, methods, and constructors, making them powerful for representing a fixed set of related values. This guide walks you through creating and using enums in Java, from the basic syntax to advanced features like methods and constructors.
What You’ll Need
- Java Development Kit (JDK) installed (version 8 or later is fine; any recent version works).
- A text editor or an Integrated Development Environment (IDE) like IntelliJ IDEA, Eclipse, or VS Code.
- Basic familiarity with Java classes and methods.
Step-by-Step
- Create a new Java file. In your project, create a new file named after the enum you want. For example, if you want an enum for days of the week, name the file
Day.java. The file name must match the enum name exactly. - Declare the enum. Use the
enumkeyword followed by the name. The enum body is enclosed in curly braces. Inside, list the constants separated by commas. For example:public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }This is the simplest form of an enum.
- Use the enum in code. You can declare a variable of the enum type and assign one of the constants. For example:
Day today = Day.MONDAY; System.out.println(today); // prints MONDAYEnums are often used in switch statements. For example:
switch (today) { case MONDAY: System.out.println("Start of the work week"); break; case FRIDAY: System.out.println("Almost weekend"); break; default: System.out.println("Midweek"); } - Add fields and a constructor (optional). To attach data to each constant, add fields and a constructor. For example, a
Planetenum with mass and radius:public enum Planet { MERCURY(3.303e23, 2.4397e6), VENUS(4.869e24, 6.0518e6), EARTH(5.976e24, 6.378e6); 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; } }Each constant is created by calling the constructor with the given arguments. The constructor must be private (or package-private) because enums cannot be instantiated externally.
- Add methods to the enum. You can define instance methods that use the fields. For example, to compute surface gravity:
public double surfaceGravity() { double G = 6.67430e-11; // gravitational constant return G * mass / (radius * radius); }Then call it like:
Planet.EARTH.surfaceGravity(). - Override methods if needed. Enums can override methods like
toString()orcompareTo()(thoughcompareTois final). For example, to display a friendly label:@Override public String toString() { return name().charAt(0) + name().substring(1).toLowerCase(); }This would make
Day.MONDAY.toString()return “Monday”. - Use enum-specific methods. Java provides built-in methods like
values()(returns an array of all constants) andvalueOf(String)(returns the constant with that name). For example:for (Day d : Day.values()) { System.out.println(d); } Day day = Day.valueOf("MONDAY");Note that
valueOfthrowsIllegalArgumentExceptionif the name doesn’t match exactly. - Use enums in collections and maps. Enums work well with
EnumSetandEnumMapfor efficient operations. For example:EnumSet<Day> weekend = EnumSet.of(Day.SATURDAY, Day.SUNDAY); EnumMap<Day, String> schedule = new EnumMap<>(Day.class); schedule.put(Day.MONDAY, "Gym");
Common Mistakes
- Forgetting the semicolon after the constant list when adding fields or methods. If you add anything after the constants, you must put a semicolon after the last constant. For example,
EARTH(5.976e24, 6.378e6);. - Using a public constructor. Enum constructors must be private or package-private. Making them public causes a compile error.
- Calling
newon an enum. You cannot instantiate an enum withnew. It’s a compile-time error. - Using
==vsequals(). For enums,==works fine because each constant is a singleton. But usingequals()is also safe. Avoid mixing them in a way that confuses readers. - Naming constants with lowercase. By convention, enum constants are uppercase with underscores (e.g.,
HIGH_PRIORITY). Not following this is not an error but is poor style.
Tips
- Use enums for fixed sets. If you have a set of values that won’t change (like statuses, categories), use an enum instead of a
Stringorintconstant. This gives you type safety and compile-time checking. - Add behavior to enums. Enums can have abstract methods that each constant implements. For example, an
Operationenum withplus,minus, etc., each overriding anapplymethod. This is a clean way to avoid switch statements. - Use
values()carefully. Thevalues()method returns a new array each time, so don’t store it if you need a stable list. UseArrays.asList(MyEnum.values())if you need a list. - Implement interfaces. Enums can implement interfaces, which is useful when you want to treat different enums polymorphically.
- Use
EnumSetandEnumMap. They are more efficient thanHashSet/HashMapfor enum keys, and they provide useful methods likerange.
Troubleshooting
- Compile error: “enum types cannot be instantiated” — You tried to use
newon an enum. Remove thenewand just use the constant name. - Compile error: “constructor X is already defined” — You likely have duplicate constructors or mismatched argument lists. Check that each constant’s arguments match the constructor parameters.
- Compile error: “illegal start of expression” — This often happens when you forget the semicolon after the constant list and then try to declare a field. Add a semicolon after the last constant.
- Runtime error:
IllegalArgumentExceptionfromvalueOf— The string you passed doesn’t match any constant name exactly (case-sensitive). Ensure the string matches the constant name, including case. - Enum not recognized in switch — Make sure you are using the enum type in the switch expression, not a String or int. Also, in the case labels, use the constant name without the enum prefix (e.g.,
case MONDAY:, notcase Day.MONDAY:).
Frequently Asked Questions
- Can an enum have multiple fields? Yes, an enum can have any number of fields, as long as you provide a constructor that initializes them. Each constant must call the constructor with appropriate arguments.
- Can an enum be extended or subclassed? No, enums are implicitly final. You cannot extend an enum, and you cannot define an enum as a subclass of another enum. However, an enum can implement interfaces.
- What is the difference between
enumandEnum?enumis the keyword to declare an enum type.Enumis the abstract base class that all enums inherit from. You rarely useEnumdirectly; it’s used internally. - Can I use an enum in a HashMap? Yes, you can use an enum as a key in a
HashMap, but it’s more efficient to useEnumMapbecause it uses an array internally and is faster. - How do I convert a String to an enum? Use the static
valueOf(String)method, e.g.,Day.valueOf("MONDAY"). If the string might not match, catchIllegalArgumentExceptionor use a loop withvalues(). - Can an enum have static methods? Yes, enums can have static methods, just like regular classes. For example, you might add a static factory method that returns a default enum value.
Related
- Gantt Minimalist Excel Template: How to Build One
- What Is a Conditional Format? Excel Rules Explained
- How to Randomly Generate Numbers in Java
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Clear Cache in Microsoft Outlook: Windows, Mac & MobileTo clear cache in the Microsoft Outlook app, use the method for your device: repair or reset new…
- Generate Random Number String: How to Do ItTo generate a random number string, use a dedicated random string generator tool, a programming language’s built-in random…
- Excel Shortcut to Select the Rest of a Column DownIn Excel for Microsoft 365 on Windows, press Ctrl+Shift+Down Arrow to extend a selection downward from the active…
- How to Insert an Image in Microsoft Excel: Step-by-StepTo insert an image in Microsoft Excel for Microsoft 365 on Windows, select the worksheet, open Insert >…
- Select an Entire Row in Excel With Shift+SpaceTo select an entire row in Excel, click any cell in that row and press Shift+Space on Windows.…
- Excel Export CSV With Quotes: How It WorksTo export a worksheet as a CSV in Excel for Microsoft 365 on Windows, choose File > Save…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.