Java

How to Use Java Enums in Switch Statements

In programming, sometimes we want to represent the fixed size of the constant. For that purpose, Java provides the Java enums, which are special classes that enable the variable to set the predefined constant. The defined variable must be assigned one or more values in capital letters and separated with commas.

This post will explain:

What are Enums in Java?

Java enums are the special classes that consist of the unchangeable variable and constant. To make an enum, utilize the “enum” keyword instead of interface or class, and use the comma for separating the constants. Furthermore, they should always be in uppercase letters.

How to Utilize Java Enums in Switch Statements?

To utilize the Java enums in switch statements, follow the below-stated example.

First of all, create an enum class and add the constant in uppercase separated with commas:

enum Skill {

 NEW,
 AVERAGE,
 PROFESSIONAL,
 EXPERT
}

Then, declare a class object with the corresponding value:

Skill testSkill = Skill.EXPERT;

Utilize the switch statement and now define different cases based on the added constant values in the “skill” class. Moreover, the “println()” method is used to display the output on the console, and the “break” keyword stop execution whenever the specified case has been met:

switch(testSkill) {
 case NEW:
 System.out.println("New");
  break;
 case AVERAGE:
 System.out.println("Average");
  break;
 case PROFESSIONAL:
  System.out.println("Professional");
  break;
 case EXPERT:
 System.out.println("Expert");
}

According to the given code, the switch statement has checked all of the given cases sequentially and printed out “Expert” on the console:

That’s all about using the Java enums in switch statements.

Conclusion

To use the Java enums in switch statements, first, create an enum class and add the constant in uppercase, separated with commas. Then, define the class and add value to the class. Lastly, utilize the “switch” statement based on the added constant valued in the “skill” class. This post has demonstrated the method for using Java enums in switch statements.

About the author

Hafsa Javed