Enumerations or Java Enum serve the purpose of representing a group of named constants in a programming language.
To create an enum, use the enum keyword
Declaration of enum in Java
Enum declaration can be done outside a class or inside a class but not inside a method.[TBD]
- Declaration outside the class
// A simple enum example where enum is declared
// outside any class (Note enum keyword instead of
// class keyword)
enum Color {
RED,
GREEN,
BLUE;
}
public class Test {
// Driver method
public static void main(String[] args) {
Color c1 = Color.RED;
System.out.println(c1);
}
}
2. Declaration inside a class
// enum declaration inside a class.
public class Test {
enum Color {
RED,
GREEN,
BLUE;
}
// Driver method
public static void main(String[] args) {
Color c1 = Color.RED;
System.out.println(c1);
}
}
3. Enum in a Switch Statement
Enums can be used in switch statements to handle different cases based on the enum constants.
// Java Program to implement
// Enum in a Switch Statement
import java.io.*;
// Driver Class
class GFG {
// Enum Declared
enum Color {
RED,
GREEN,
BLUE,
YELLOW;
}
// Main Function
public static void main(String[] args) {
Color var_1 = Color.YELLOW;
// Switch case with Enum
switch (var_1) {
case RED:
System.out.println("Red color observed");
break;
case GREEN:
System.out.println("Green color observed");
break;
case BLUE:
System.out.println("Blue color observed");
break;
default:
System.out.println("Other color observed");
}
}
}
Reference link :
https://www.geeksforgeeks.org/enum-in-java/