Enum in Java
In Java, an enum
(short for enumeration) is a special data type that enables a variable to be a set of predefined constants. It’s used when you want to represent a fixed set of related constants in a type-safe way.
✅ Why Use enum
in Java?
- Groups constants into a single type
- Type-safe (no invalid values allowed)
- Can include fields, constructors, and methods
- Great for switch statements and control logic
🔧 Basic Syntax
Usage:
🚀 Enums in switch
🛠️ Enum with Fields and Methods
Usage:
📋 Enum Features Summary
Feature | Supported in Java Enum |
---|---|
Type-safe constants | ✅ Yes |
Switch-case usage | ✅ Yes |
Fields and methods | ✅ Yes |
Constructors | ✅ Yes (private only) |
Extending a class | ❌ No (enums extend java.lang.Enum ) |
Implementing interface | ✅ Yes |
📚 Real-World Use Cases
-
Order status (
NEW
,SHIPPED
,DELIVERED
) -
User roles (
ADMIN
,USER
,GUEST
) - Days, months, categories