![]() |
VOOZH | about |
In Java, enum is a special data type used to define a fixed set of constant values in a type-safe way. It improves code clarity by replacing numeric or string constants with meaningful names. Enums are commonly used when a variable can have only a limited set of predefined values.
RED
Enum declaration can be done outside a class or inside a class but not inside a method.
enum EnumName {
CONSTANT1, CONSTANT2, CONSTANT3;
}
As we have seen in the above example, enums can be declared outside a class and accessed directly
Enums can also be declared inside a class but not inside a method.
RED
There are certain properties followed by Enum as mentioned below:
Enums can be used in switch statements to handle different cases based on the enum constants.
Other color
Enums can have constructors and methods, executed separately for each constant
Constructor called for: RED Constructor called for: GREEN Constructor called for: BLUE Color is: RED
Enums can declare abstract methods that each constant must implement.
1st day 5th day
Use EnumType.values() to loop through all enum constants.
RED GREEN BLUE
EnumSet.range() allows iteration over a specific range of enum constants.
TUESDAY WEDNESDAY THURSDAY FRIDAY
We can combine enums with regular classes to organize your program logic. An enum can be a member variable in a class, and methods can perform actions based on the enum value.
Mondays are tough Wednesday are okay Fridays are exciting Saturdays are relaxing Sunday are for rest
Explanation:
NOTE: The new keyword is used because EnumTest is a regular class, not an enum, so we create instances and pass the enum value to its constructor.