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:

MONDAY

Using Enum in Switch Statement


 

✔ Output:

High level

 Enum with Methods and Fields

Enums can have:

  • Fields

  • Constructors

  • Methods
    (All enum constructors are private automatically.)


 

✔ Output:

200
ERROR

Loop Through Enum Values


 

✔ Output:

MON
TUE
WED
THU
FRI
SAT
SUN

Comparison with Enum

Enums can be compared using == because they are singleton objects.


 

✔ Output:

Same color

🛠 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:

Order is currently: SHIPPED

🎯 Summary

Feature Yes / No
Fixed predefined values
Can have constructors and methods
Supports iteration
Allows object creation

You may also like...