HOME HTML EDITOR C JAVA PHP

Java Enum: Working with Fixed Constants

A Java Enum is a special data type that enables a variable to be a set of predefined constants. Common examples include compass directions (NORTH, SOUTH, EAST, WEST), days of the week, or the states of a process (PENDING, RUNNING, COMPLETED). Enums increase Type Safety and make your code significantly more readable.

In this tutorial, we will explore the following aspects of Java Enums:

1. Defining and Using a Basic Enum

An enum is created using the enum keyword. By convention, enum constants should be in UPPERCASE because they are final constants.

enum Level {
  LOW, MEDIUM, HIGH
}

To access the constants, you use the dot syntax: Level myVar = Level.MEDIUM;.

Why not just use Static Final variables?

Using public static final int LOW = 1; is risky because a method could accidentally accept any integer (like 99), causing bugs. An Enum ensures that only valid Level values can be passed to your methods.

2. Enums in Switch Statements

Enums are a perfect match for switch statements. Because the compiler knows exactly what the possible values are, it makes the logic clean and easy to follow.

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;
}

3. Built-in Methods for Enums

Every Java Enum automatically inherits methods from the java.lang.Enum class. The most useful ones are:

Method Description
values() Returns an array of all enum constants. Great for loops.
ordinal() Returns the position of a constant (starting from 0).
valueOf(String) Converts a String into the corresponding enum constant.

4. Advanced: Enums as Classes

In Java, Enums are much more than just a list of names. They can have attributes, constructors, and methods. This allows you to associate data with each constant.

enum TrafficLight {
  RED("STOP"), GREEN("GO"), YELLOW("WAIT");

  private String action;

  // Constructor (Always private)
  TrafficLight(String action) {
    this.action = action;
  }

  public String getAction() {
    return this.action;
  }
}
Key Rule: Enum constructors are always private or package-private. You cannot create a new enum constant using new. They are fixed at compile time.

5. EnumSet and EnumMap

Because Enum constants have a fixed range and unique ordinals, Java provides specialized collections that are extremely high-performance:

6. Differences Between Classes and Enums

Feature Class Enum
Instantiation Multiple objects using new. Fixed constants, no new.
Inheritance Can extend another class. Cannot extend another class (already extends Enum).
Interfaces Can implement multiple interfaces. Can implement multiple interfaces.

7. Interview Preparation: The Deep Questions

Q: Why can't an Enum extend another class?
A: Because all Enums implicitly extend java.lang.Enum. Since Java doesn't support multiple inheritance for classes, your Enum cannot extend anything else.

Q: Is Enum thread-safe?
A: Yes, Enum constants are implicitly static and final, and the JVM ensures they are instantiated in a thread-safe manner. This is why Enums are often used to implement the Singleton Pattern.

Q: Can we have abstract methods in an Enum?
A: Yes! You can define an abstract method in the Enum and provide a specific implementation for each constant. This is known as Constant-Specific Class Bodies.

Final Verdict

Java Enums are a masterclass in Type Safety. They allow you to define a restricted set of values while still maintaining all the power of a standard Java class. Whether you're handling state machines, configurations, or simple flags, Enums make your code robust and self-documenting.

Next: Handling User Input (Scanner) →