Java Enums


Enums

A special enum "category" representing a group of constants (a fixed variable, such as a final variable).

To create an enum, use the enum keyword (instead of a class or visual link), and break constants with commas. Note that it must be capitalized:


Example
enum Level {
            LOW,
            MEDIUM,
            HIGH
          }
          

You can access enum constants with the dot syntax:

Level myVar = Level.MEDIUM;

The word Enum is short for "statistics", meaning "directly listed".


Enum inside a Class

You can also have enum within the class:


Example
public class Main {
            enum Level {
              LOW,
              MEDIUM,
              HIGH
            }
          
            public static void main(String[] args) {
              Level myVar = Level.MEDIUM; 
              System.out.println(myVar);
            }
          }
          

The output will be:

MEDIUM


Enum in a Switch Statement

Enums are commonly used in switch statements to check the corresponding values:


Example
enum Level {
            LOW,
            MEDIUM,
            HIGH
          }
          
          public class Main {
            public static void main(String[] args) {
              Level myVar = Level.MEDIUM;
          
              switch(myVar) {
                case LOW:
                  System.out.println("Low level");
                  break;
                case MEDIUM:
                   System.out.println("Medium level");
                  break;
                case HIGH:
                  System.out.println("High level");
                  break;
              }
            }
          }
          

The output will be:

Medium level


Loop Through an Enum

The enum type has a values() method, which returns a list of all enum constants. This method is useful if you want to connect to enum constants:


Example
for (Level myVar : Level.values()) {
            System.out.println(myVar);
          }
          

The output will be:

LOW
MEDIUM
HIGH

Difference between Enums and Classes

Enum can, as a class, have signs and patterns. The only difference is that the enum constants are public, static and final (unchangeable - they cannot be removed).

Enum cannot be used to create objects, nor can it expand other classes (but can also use communication).

Why And When To Use Enums?

Use enums if you have numbers that you know will not change, such as days of the month, days, colors, deck of cards, etc.