Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

enum
java

What are enums in Java?

Educative Answers Team

An enum is a special class that represents a group of constants.

Enum keyword is used to create an enum. The constants declared inside are separated by a comma and should be in upper case.

svg viewer

Example

An enum can be declared inside a class or outside a class. In the example below, we are declaring it inside a class:

class MyClass { 
  enum color {  // declaring an enum using the enum keyword 
    // defining enum constants using the enum keyword
    RED,
    GREEN,
    BLUE
  }

  public static void main(String[] args) { 
    
    color x = color.GREEN; // storing
    System.out.println(x); 
  } 
}

Properties of enum

  1. Similar to a class, an enum can have objects and methods. The only difference is that enum constants are public, static and final by default. Since it is final, we can’t create child enums
  2. It cannot extend other classes since it already extends the java.lang.Enum class.
  3. It can implement interfaces.
  4. The enum objects cannot be created explicitly and hence the enum constructor cannot be invoked directly.
  5. It can only contain concrete methods and no abstract methods.

Where to use enum?

enum is used for values that are not going to change e.g. names of days, colors in a rainbow, number of cards in a deck etc.

enum is commonly used in switch statements and below is an example of it:

class MyClass { 
  enum color {  // declaring an enum using the enum keyword 
    // defining enum constants using the enum keyword
    RED,
    GREEN,
    BLUE
  }

  public static void main(String[] args) { 

    color x = color.GREEN; // storing value 
    switch(x) {
      case RED:
        System.out.println("x has RED color");
        break;
      case GREEN:
        System.out.println("x has GREEN color");
        break;
      case BLUE:
        System.out.println("x has BLUE color");
        break;
    }
  } 
}

RELATED TAGS

enum
java
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring