What is enum in Java?
An enum is a special "data type" that used to create our own datatype like classes and It represents a group of constants (a variable that does not change).
The enum is short for "enumerations", which means "specifically listed" and the Enum data also known as Enumerated Data Type.
# Defining Java enum
Instead of C/C++, in java programming language enum types are more powerful. Here, we can define an enum both inside and enum outside the class but not inside a Method
"Rules" to defing enum in Java:
To create an enum in Java, use the enum keyword (instead of class or interface), and separate the constants with a comma(,).
The enum can be defined within or outside the class because it is similar to a class. The semicolon (;) at the end of the enum constants are optional
Because enum are constants, the names of an enum type's fields are in uppercase letters.
Syntax :
enum Directions { EAST, WEST, NORTH, SOUTH; }
OR
enum Directions { EAST, WEST, NORTH, SOUTH }
# Access Java enum
You can access enum constants with the help of dot operator.
Syntax :
Directions myVar = Directions.NORTH;
Let's see, the simple examples of enum Java :
1.) enum inside class
➤ Example 2: Defined enum inside class
class EnumExample {
//Defining the enum inside the class
enum Directions{
EAST, WEST, NORTH, SOUTH
} //semicolon(;) is optional here
public static void main(String args[]) {
Directions myvar= Directions.NORTH;
System.out.println(myvar);
}
}
Output :
NORTH
Comments