What is enum in Java: Simple Explanation and Example
enum in Java is a special type that lets you define a fixed set of named constants, like days of the week or colors. It helps make your code clearer and safer by grouping related values under one type.How It Works
Think of an enum as a list of named options you can choose from, like a menu with fixed choices. Instead of using random numbers or strings to represent these options, enum gives each choice a clear name and groups them together.
When you use an enum, Java treats these named constants as special objects. This means you can compare them easily, use them in switch statements, and avoid mistakes like typos or invalid values.
For example, if you have an enum for colors, you can only pick from the colors you defined, making your program more reliable and easier to understand.
Example
This example shows an enum for the days of the week and how to use it in a simple program.
public class EnumExample { enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY } public static void main(String[] args) { Day today = Day.WEDNESDAY; switch (today) { case SATURDAY, SUNDAY -> System.out.println("It's the weekend!"); default -> System.out.println("It's a weekday."); } } }
When to Use
Use enum when you have a fixed set of related values that don’t change, like days, months, directions, or states. It helps avoid errors by limiting possible values and makes your code easier to read and maintain.
For example, in a traffic light program, you can use an enum to represent the light colors (RED, YELLOW, GREEN) instead of using strings or numbers. This way, the program only accepts valid colors and is clearer to anyone reading the code.
Key Points
- Enums group related constants under one type for clarity.
- They prevent invalid values by restricting choices.
- Enums can have methods and fields for more complex behavior.
- Use enums in switch statements for clean, readable code.