An enum
is a special class that represents a group of constants.
Enum keyword is used to create an enum
. The constants declared inside are separated by a comma and should be in upper case.
An enum
can be declared inside a class or outside a class. In the example below, we are declaring it inside a class:
class MyClass { enum color { // declaring an enum using the enum keyword // defining enum constants using the enum keyword RED, GREEN, BLUE } public static void main(String[] args) { color x = color.GREEN; // storing System.out.println(x); } }
enum
can have objects and methods. The only difference is that enum
constants are public
, static
and final
by default. Since it is final
, we can’t create child enumsjava.lang.Enum
class.enum
objects cannot be created explicitly and hence the enum
constructor cannot be invoked directly.
enum
is used for values that are not going to change e.g. names of days, colors in a rainbow, number of cards in a deck etc.
enum
is commonly used in switch statements and below is an example of it:
class MyClass { enum color { // declaring an enum using the enum keyword // defining enum constants using the enum keyword RED, GREEN, BLUE } public static void main(String[] args) { color x = color.GREEN; // storing value switch(x) { case RED: System.out.println("x has RED color"); break; case GREEN: System.out.println("x has GREEN color"); break; case BLUE: System.out.println("x has BLUE color"); break; } } }
RELATED TAGS
View all Courses