Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
community creator

How to use Java enums in switch statements

Tarun Telang

Enum (enumeration class)

An enum class is a special class used to represent a group of constants.

It can be declared using the enum keyword, as shown below:

enum Skill {
    BEGINNER,
    INTERMEDIATE, 
    PROFICIENT,
    EXPERT
}
  • enum constants are public, static, and final by default.
  • enum constants are accessed using dot syntax.
  • An enum class can have attributes and methods, in addition to constants.
  • You cannot create objects of an enum class, and it cannot extend other classes.
  • An enum class can only implement interfaces.

Enums in switch case

Enums can be used in a switch-case statement, as shown below:

public class Main { 
  enum Skill {
    BEGINNER,
    INTERMEDIATE, 
    PROFICIENT,
    EXPERT
  }
  public static void main(String[] args) {
    Skill mySkill = Skill.INTERMEDIATE;
    switch(mySkill) {
      case BEGINNER:
        System.out.println("Beginner");
        break;
      case INTERMEDIATE:
         System.out.println("Intermediate");
        break;
      case PROFICIENT:
        System.out.println("Proficient");
        break;
      case EXPERT:
        System.out.println("Expert");
    }
  }
}

RELATED TAGS

java
community creator
RELATED COURSES

View all Courses

Keep Exploring