How to Create Enum in Java: Syntax and Examples
In Java, you create an
enum by using the enum keyword followed by the name and a list of constant values inside curly braces. Enums represent a fixed set of constants and can be used like classes with methods and fields.Syntax
An enum is declared using the enum keyword followed by the enum name and a list of constants separated by commas inside curly braces.
- enum: keyword to define an enum type
- Name: the name of the enum type (like a class name)
- Constants: fixed values separated by commas
java
public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }
Example
This example shows how to create an enum Day and use it in a simple program to print a message based on the day.
java
public class EnumExample { public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } public static void main(String[] args) { Day today = Day.WEDNESDAY; switch (today) { case MONDAY: System.out.println("Start of the work week."); break; case FRIDAY: System.out.println("Almost weekend!"); break; case SATURDAY: case SUNDAY: System.out.println("It's the weekend!"); break; default: System.out.println("Midweek day."); break; } } }
Output
Midweek day.
Common Pitfalls
Common mistakes when creating enums include:
- Not using uppercase letters for enum constants (by convention, constants are uppercase).
- Trying to assign values directly like variables (enums are constants).
- Forgetting the semicolon when adding fields or methods after constants.
- Using enums without understanding they are types, not just constants.
java
/* Wrong: enum constants should be uppercase and no assignment */ public enum Color { red = 1, green = 2, blue = 3; // This is invalid } /* Right way: */ public enum Color { RED, GREEN, BLUE; }
Quick Reference
| Feature | Description |
|---|---|
| Declaration | Use enum Name { CONSTANT1, CONSTANT2, ... } |
| Constants | Fixed set of named values, usually uppercase |
| Usage | Enums can be used in switch statements and comparisons |
| Methods | Enums can have fields, constructors, and methods |
| Convention | Enum names are PascalCase, constants are UPPERCASE |
Key Takeaways
Use the
enum keyword to define a fixed set of constants in Java.Enum constants are usually written in uppercase letters by convention.
Enums can be used in
switch statements for clear, readable code.You can add fields and methods to enums for more complex behavior.
Remember to use enums as types, not just as simple constants.