In java, if a variable should hold a value from predefined set of constants , we can use enum for define those constants set.We must always use enums when a variable can only take one out of a small set of possible values. Enum was introduced by Java version five. Let's say we want to define a variable as month. We know that there are only twelve constant values which month variable can have. So, we can define an enum for this situation as shown in the below code segment.
This is the output of above programme :
Previous month was FEBRUARY
This month is MARCH
Next month is APRIL
JANUARY
FEBRUARY
MARCH
APRIL
MAY
JUNE
JULY
AUGUST
SEPTEMBER
OCTOMBER
NOVEMBER
DECEMBER
Enum class provide a static method as values() which returns all the emum values into an array and we can iterate through that array by using for each loop.
Further we can define enums with parameter values. To crate a this type of enum, we have to create an enum class as shown in below code segment.
This is the output of above programme :
COLOMBO university is situated in colombo with 8 faculties
RUHUNA university is situated in matara with 5 faculties
JAFFNA university is situated in jaffna with 9 faculties
UWA university is situated in badhulla with 5 faculties
Advantages Of Using Enums :
1.Enum is type-safe so we can't assign anything else other than predefined Enum constants to an Enum variable.
2.Enum can be used as an argument on switch statment like int,char or string.
No comments:
Post a Comment