Table of contents
Enums in java are a special type of data type that lets a variable only have a set of predefined constants. The most common example are days in a week ( MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY ) or cards in a standard deck, seasons etc. Because they are constants, the names of an enum type's fields are in uppercase letters only. Constants in enums are static and final implicitly.
Declaration
The enum declaration defines a class of enum type which implicitly extends java.lang.Enum. The enum class body can include methods and fields.
enum Week {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
Java compiler automatically adds some methods during compile time to the enum class eg static method values() which returns an array containing all the values declared in enum class in same order.
Usage
Enums are useful when we know all the possible values a variable can have.
Example
class Main{
enum Week {
MONDAY , TUESDAY , WEDNESDAY , THURSDAY , FRIDAY , SATURDAY
}
public static void main(String[] args)
{
for(Week day: Week.values())
System.out.println(day);
}
}
Program
I have made a simple small Game which uses enums in it. Once I coded that, It made my concepts about enums clear and I was able to write my first article. You can check it out here-
Ths is my first article, let me know how much did you liked my article. Hopefully, will be writing more articles soon.