An enum in Java is a special class that represents a fixed set of constants. You define it with the enum keyword, and it gives you type-safe constants—like days of the week, order statuses, or error codes—that the compiler checks for you. This guide walks you through creating a basic enum, adding fields and methods, and using it in your code. You only need a Java development environment (JDK 8 or later) and a text editor or IDE.
What You’ll Need
- Java Development Kit (JDK) installed (version 8 or newer).
- A text editor or an IDE like IntelliJ IDEA, Eclipse, or VS Code.
- Basic familiarity with Java classes and methods.
Step-by-Step
- Create a new Java file. Name it after your enum, e.g.,
Day.java. In Java, the file name must match the public type name. - Declare the enum. Start with the
enumkeyword, then the name, then a pair of braces. Inside the braces, list the constants separated by commas. For example:public enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY } - Add a semicolon if you add anything else. If your enum has only constants, no semicolon is needed. But if you add fields, constructors, or methods, put a semicolon after the last constant.
- Add fields and a constructor (optional). Enums can hold data. For instance, to give each day a number:
public enum Day { MONDAY(1), TUESDAY(2), WEDNESDAY(3), THURSDAY(4), FRIDAY(5), SATURDAY(6), SUNDAY(7); private final int number; Day(int number) { this.number = number; } public int getNumber() { return number; } }The constructor must be
privateor package-private—you cannot usepublicorprotected. - Add methods (optional). You can add regular methods or override methods like
toString(). For example, a method to check if it’s a weekend:public boolean isWeekend() { return this == SATURDAY || this == SUNDAY; } - Use the enum in another class. Create a
Main.javaand reference the enum:public class Main { public static void main(String[] args) { Day today = Day.WEDNESDAY; System.out.println("Today is " + today); System.out.println("Day number: " + today.getNumber()); System.out.println("Is it weekend? " + today.isWeekend()); } } - Compile and run. In the terminal, run
javac Day.java Main.javathenjava Main. You should see the output. - Iterate over enum values. Use the built-in
values()method to loop through all constants:for (Day d : Day.values()) { System.out.println(d); } - Switch on an enum. Enums work perfectly in
switchstatements:switch (today) { case MONDAY: System.out.println("Start of work week"); break; case FRIDAY: System.out.println("TGIF"); break; default: System.out.println("Midweek"); }Note: in a switch, use the constant name without the enum type prefix.
Common Mistakes
- Forgetting the semicolon when adding fields or methods after the constants. Without it, the compiler throws an error.
- Using
newto create an enum instance. Enums are instantiated automatically; you cannot donew Day(). - Making the constructor
public. The constructor must beprivateor package-private. A public constructor causes a compile error. - Comparing enums with
==vsequals(). Both work because each constant is a singleton, but==is the idiomatic and safer choice. - Using a reserved keyword as a constant name. For example,
enumorclasscannot be constant names. - Forgetting to import the enum if it’s in a different package. Use
import com.example.Day;.
Tips
- Use enums for fixed sets. They’re ideal for things like statuses, roles, or configuration keys.
- Add behavior to enums. Instead of using if-else chains elsewhere, put logic inside the enum.
- Use
valueOf()to convert a string to an enum. For example,Day.valueOf("MONDAY")returnsDay.MONDAY. It throwsIllegalArgumentExceptionif the string doesn’t match. - Consider abstract methods for different behavior per constant. You can declare an abstract method and override it in each constant’s body, but that’s advanced—use it sparingly.
- Keep enums small. If you need many constants with complex logic, consider a class hierarchy instead.
Troubleshooting
- Compile error: ‘}’ expected or ‘;’ expected. Check that you added a semicolon after the last constant if you have fields or methods.
- Compile error: illegal start of expression. Make sure the enum is declared at the top level of the file or inside a class, not inside a method.
- Runtime error: NoSuchMethodError or ClassNotFoundException. Ensure the file name matches the enum name exactly, and that you compiled all files together.
- Cannot find symbol when using
values(). This method is implicitly defined, but if you have a field namedvalues, it can conflict. Avoid naming fieldsvalues. - Enum constant not recognized in switch. In a switch, use the constant name without the enum type prefix. If you write
case Day.MONDAY, it won’t compile.
Frequently Asked Questions
- Can I extend an enum? No. All enums implicitly extend
java.lang.Enum, and Java doesn’t allow multiple inheritance. You cannot extend an enum. - Can an enum implement an interface? Yes. An enum can implement interfaces, which is useful for defining common behavior across constants.
- How do I get the name of an enum constant as a string? Use the
name()method, e.g.,Day.MONDAY.name()returns"MONDAY". ThetoString()method also returns the name by default, but you can override it. - Can I have multiple constructors in an enum? Yes, you can overload constructors, but the arguments must match what you pass in the constant declarations.
- What’s the difference between
==andequals()for enums? Both work because each constant is a singleton, but==is preferred because it’s null-safe and faster. Use==for comparisons. - Can I use an enum in a HashMap or HashSet? Yes, enums are good keys because they are immutable and have stable hash codes. You can also use
EnumMapandEnumSetfor better performance.
Related
- Colour the Traffic Light Worksheet: Uses & Tips
- Reaction Time Test Traffic Light: How It Works
- How to Say “Update” in 12 Languages
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Databricks STRING Data Type: Uses and ExamplesIn Databricks, STRING is the data type for text: it holds sequences of characters such as names, descriptions,…
- How to Duplicate an Excel Document on Windows SafelyTo duplicate an Excel document on Windows, open it in Excel and choose File > Save As >…
- What Is the AND Operator in JavaScript? (&&)The AND operator in JavaScript is the double ampersand &&, and it returns true only when both operands…
- Excel Text to Columns: What the Text Qualifier DoesIn Excel for Microsoft 365 on Windows, the Text qualifier in Data > Text to Columns tells Excel…
- Excel Not Highlighting Cells When Selected? FixesIf Excel is not visibly highlighting a selected cell, first press Esc to leave edit mode, then click…
- Excel Cell Calendar Popup: What Works and What Doesn’tIn Excel for Microsoft 365 on Windows, there is no universal built-in calendar popup that appears when you…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.