Java Enums
Java Enums
A Java Enum (Enumeration) is a special data type used to define a fixed set of constant values.
It is commonly used when you need predefined values that do not change, such as days of the week, months, directions, etc.
Enums make code readable, type-safe, and error-free.
Basic Enum Example
✔ Output:
Using Enum in Switch Statement
✔ Output:
Enum with Methods and Fields
Enums can have:
-
Fields
-
Constructors
-
Methods
(All enum constructors are private automatically.)
✔ Output:
Loop Through Enum Values
✔ Output:
Comparison with Enum
Enums can be compared using == because they are singleton objects.
✔ Output:
🛠 Why Use Enums?
| Feature | Benefit |
|---|---|
| Type-safe | No invalid values allowed |
| Readable | Meaningful names |
| Predefined values | Good for controlled options |
| Useful in switch | Cleaner conditional logic |
🔥 Real-Life Use Case: Order Status
✔ Output:
🎯 Summary
| Feature | Yes / No |
|---|---|
| Fixed predefined values | ✔ |
| Can have constructors and methods | ✔ |
| Supports iteration | ✔ |
| Allows object creation | ❌ |
