Java Enum in Switch Statement
Enumerations (enums) are a powerful and clear way to represent a fixed set of named constants in Java.
Enums are used in Switch statements due to their type safety and readability.
Example:
Use of Enum in Switch
// Java Program to Illustrate Use of Enum
// in Switch Statement
// Class
public class GFG {
// Enum
public enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat }
// Main driver method
public static void main(String args[])
{
// Enum
Day[] DayNow = Day.values();
// Iterating using for each loop
for (Day Now : DayNow) {
// Switch case
switch (Now) {
// Case 1
case Sun:
System.out.println("Sunday");
// break statement that hault further
// execution once case is satisfied
break;
// Case 2
case Mon:
System.out.println("Monday");
break;
// Case 3
case Tue:
System.out.println("Tuesday");
break;
// Case 4
case Wed:
System.out.println("Wednesday");
break;
// Case 5
case Thu:
System.out.println("Thursday");
break;
// Case 6
case Fri:
System.out.println("Friday");
break;
// Case 7
case Sat:
System.out.println("Saturday");
}
}
}
}
Output
Sunday Monday Tuesday Wednesday Thursday Friday Saturday
Switch Statements in Java
The switch statement in Java is a multi-way branch statement. In simple words, the Java switch statement executes one statement from multiple conditions.
It is like an if-else-if ladder statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. The expression can be a byte, short, char, or int primitive data type. It tests the equality of variables against multiple values.