BCA / B.Tech 10 min read

Enum Data Type in Java

What is an Enum in Java?

An enum (short for enumeration) is a special data type that represents a fixed set of constants. It is used when a variable can only take one value from a small, predefined set of possible values. Common examples include days of the week, compass directions, or states in a process (e.g., PENDING, PROCESSING, COMPLETED). Enums enhance code readability and prevent errors from using invalid values.

Defining and Using an Enum:

An enum is defined using the enum keyword. The constants are listed in uppercase letters.


// Define an enum for pizza sizes
public enum Size {
    SMALL, MEDIUM, LARGE, EXTRA_LARGE
}

public class PizzaOrder {
    public static void main(String[] args) {
        // Use the enum constant directly
        Size pizzaSize = Size.LARGE;
        
        System.out.println("You ordered a " + pizzaSize + " pizza.");
    }
}
        

Enums in a `switch` Statement:

Enums are very powerful when used with `switch` statements, as the compiler can check if all enum constants are handled.


Size mySize = Size.MEDIUM;
switch (mySize) {
    case SMALL:
        System.out.println("Small pizza selected.");
        break;
    case MEDIUM:
        System.out.println("Medium pizza selected.");
        break;
    case LARGE:
        System.out.println("Large pizza selected.");
        break;
    default:
        System.out.println("Some other size.");
        break;
}
        

Key Features of Enums:
  • Type-Safety: You can't assign an invalid value to an enum variable. For example, Size mySize = "Small"; would cause a compile-time error.
  • Built-in Methods: Enums come with useful methods. Size.values() returns an array of all constants, allowing you to iterate through them. Size.valueOf("LARGE") converts a string to the corresponding enum constant.
  • Advanced Capabilities: An enum can have its own methods, constructors, and instance variables, making it much more powerful than simple constants.