Java Enum - Visual Explanation
❌ Without Enum
String day = "monday";
String day2 = "Monday";
String day3 = "MONDAY";
int dayCode = 1;
String day2 = "Monday";
String day3 = "MONDAY";
int dayCode = 1;
🚫 Inconsistent
🚫 Error-prone
🚫 Hard to maintain
➡️
✅ With Enum
enum Day {
MONDAY, TUESDAY, ...
}
Day today = Day.MONDAY;
MONDAY, TUESDAY, ...
}
Day today = Day.MONDAY;
✅ Consistent
✅ Type-safe
✅ Easy to use
🏗️ Enum Structure
Enum Declaration
enum
Day {MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
}
enum - keyword
Day - Enum name
MONDAY... - Constants
📝 Usage Example
Day today = Day.FRIDAY;
System.out.println(today);
System.out.println(today);
Output: FRIDAY
🔄 Switch Example
switch(today) {
case MONDAY:
print("Work day!");
break;
case SUNDAY:
print("Rest day!");
}
case MONDAY:
print("Work day!");
break;
case SUNDAY:
print("Rest day!");
}
Clean & Readable!
🎯 Why Use Enums?
🛡️
Type Safety
Prevents invalid values
📖
Readability
Code is self-documenting
🔧
Maintainable
Easy to modify and extend
⚡
Performance
Efficient memory usage
🌍 Real World Examples
🍕
Pizza Sizes
enum Size {
SMALL, MEDIUM, LARGE
}
SMALL, MEDIUM, LARGE
}
🚦
Traffic Lights
enum Light {
RED, YELLOW, GREEN
}
RED, YELLOW, GREEN
}
🎮
Game Status
enum Status {
PLAYING, PAUSED, OVER
}
PLAYING, PAUSED, OVER
}
🎓 Master Java Enums!
Use Enums for fixed sets of constants - they make your code safer, cleaner, and more professional! 🚀
0 Comments
If you have any doubts, Please let me know