Home ยป Java Enums Tutorial

Java Enums Tutorial

In Java, Enum (short for Enumeration) is a special data type that represents a fixed set of constants. Enums provide a way to define a collection of related constants in a more readable, structured, and type-safe manner.

Enums can have fields, methods, and constructors, making them more powerful than regular constants.

This tutorial covers how to use enums in Java with several code examples to help you understand how to define and use them effectively.

1. Defining a Simple Enum

To define an enum in Java, use the enum keyword, followed by the enum name and a list of constants.

Example:

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

Explanation:

Day is an enum with seven constants: SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY.
Enums are implicitly public, static, and final.

2. Using Enums in a Switch Statement

Enums can be used in switch statements just like primitive types such as int or char. This provides a clean and type-safe way to handle a set of related constants.

Example:

public class EnumSwitchExample {
    public enum Day {
        SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
    }

    public static void main(String[] args) {
        Day today = Day.WEDNESDAY;

        switch (today) {
            case MONDAY:
                System.out.println("Start of the work week!");
                break;
            case WEDNESDAY:
                System.out.println("Midweek.");
                break;
            case FRIDAY:
                System.out.println("End of the work week.");
                break;
            case SUNDAY:
            case SATURDAY:
                System.out.println("Weekend!");
                break;
            default:
                System.out.println("Weekday.");
        }
    }
}

Explanation:

Day enum is used in the switch statement to print different messages based on the day.

Output:
Midweek. (because the current day is WEDNESDAY).

3. Enum with Fields, Methods, and Constructors

Enums can have fields, methods, and constructors to store additional data and behavior. This makes enums more flexible and useful in real-world applications.

Example:

public enum Planet {
    MERCURY(3.303e+23, 2.4397e6),
    VENUS(4.869e+24, 6.0518e6),
    EARTH(5.976e+24, 6.37814e6),
    MARS(6.421e+23, 3.3972e6);

    // Fields
    private final double mass;   // In kilograms
    private final double radius; // In meters

    // Constructor
    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }

    // Method to calculate the surface gravity
    public double surfaceGravity() {
        double G = 6.67300E-11;  // Universal gravitational constant (m^3 kg^-1 s^-2)
        return G * mass / (radius * radius);
    }

    public double getMass() {
        return mass;
    }

    public double getRadius() {
        return radius;
    }
}

public class PlanetExample {
    public static void main(String[] args) {
        for (Planet planet : Planet.values()) {
            System.out.println("Planet: " + planet + ", Surface Gravity: " + planet.surfaceGravity());
        }
    }
}

Explanation:

The Planet enum contains constants with associated mass and radius values.
The surfaceGravity() method calculates and returns the surface gravity of each planet.
The values() method returns all enum constants in an array for iteration.

Output:

Planet: MERCURY, Surface Gravity: 3.7030267229659395
Planet: VENUS, Surface Gravity: 8.871391908774457
Planet: EARTH, Surface Gravity: 9.802652743337129
Planet: MARS, Surface Gravity: 3.7126290961053403

4. Enum with Overridden Methods

Enums can override methods, and you can give each constant its own implementation of the method. This is useful when you want each constant to behave differently.

Example:

public enum Operation {
    PLUS {
        public double apply(double x, double y) {
            return x + y;
        }
    },
    MINUS {
        public double apply(double x, double y) {
            return x - y;
        }
    },
    MULTIPLY {
        public double apply(double x, double y) {
            return x * y;
        }
    },
    DIVIDE {
        public double apply(double x, double y) {
            return x / y;
        }
    };

    // Abstract method
    public abstract double apply(double x, double y);
}

public class OperationExample {
    public static void main(String[] args) {
        double x = 10.0;
        double y = 5.0;

        for (Operation op : Operation.values()) {
            System.out.println(x + " " + op + " " + y + " = " + op.apply(x, y));
        }
    }
}

Explanation:

Each constant in the Operation enum overrides the apply() method to perform its specific operation.
PLUS, MINUS, MULTIPLY, and DIVIDE provide their own implementations for apply().

Output:

10.0 PLUS 5.0 = 15.0
10.0 MINUS 5.0 = 5.0
10.0 MULTIPLY 5.0 = 50.0
10.0 DIVIDE 5.0 = 2.0

5. Enum Methods

Java enums come with several built-in methods that provide additional functionality:

values(): Returns an array of all enum constants.
valueOf(String name): Returns the enum constant with the specified name.
ordinal(): Returns the position of the enum constant in its declaration (index starting from 0).
name(): Returns the name of the enum constant as a String.

Example:

public enum Color {
    RED, GREEN, BLUE
}

public class EnumMethodsExample {
    public static void main(String[] args) {
        // Using values() method
        for (Color color : Color.values()) {
            System.out.println(color + " is at index " + color.ordinal());
        }

        // Using valueOf() method
        Color selectedColor = Color.valueOf("RED");
        System.out.println("Selected color: " + selectedColor);
    }
}

Explanation:

The values() method returns an array of all constants in the Color enum.
The ordinal() method returns the position of each enum constant.
The valueOf() method retrieves the enum constant by name.

Output:

RED is at index 0
GREEN is at index 1
BLUE is at index 2
Selected color: RED

6. Enum with Interfaces

Enums can implement interfaces, which allows you to define common behavior for all enum constants.

Example:

interface Printable {
    void print();
}

public enum Shape implements Printable {
    CIRCLE {
        public void print() {
            System.out.println("This is a circle.");
        }
    },
    SQUARE {
        public void print() {
            System.out.println("This is a square.");
        }
    },
    TRIANGLE {
        public void print() {
            System.out.println("This is a triangle.");
        }
    }
}

public class InterfaceInEnumExample {
    public static void main(String[] args) {
        for (Shape shape : Shape.values()) {
            shape.print();  // Calling the method implemented in the enum
        }
    }
}

Explanation:

The Shape enum implements the Printable interface, requiring each enum constant to provide its own implementation of the print() method.

Output:

This is a circle.
This is a square.
This is a triangle.

7. Enum with Custom Methods

Enums can have custom methods just like regular classes. These methods can be used to add functionality specific to the enum constants.

Example:

public enum TrafficLight {
    RED(30), GREEN(60), YELLOW(5);

    // Field to store duration of each light
    private final int duration;

    // Constructor to initialize the duration
    TrafficLight(int duration) {
        this.duration = duration;
    }

    // Custom method to get the duration
    public int getDuration() {
        return duration;
    }

    // Method to display the traffic light
    public void displayLight() {
        System.out.println(this.name() + " light for " + duration + " seconds.");
    }
}

public class TrafficLightExample {
    public static void main(String[] args) {
        for (TrafficLight light : TrafficLight.values()) {
            light.displayLight();  // Calling custom method for each enum constant
        }
    }
}

Explanation:

Each traffic light has a duration, passed to the constructor when the enum is initialized.
The displayLight() method provides a custom message for each traffic light.

Output:

RED light for 30 seconds.
GREEN light for 60 seconds.
YELLOW light for 5 seconds.

8. Enum Comparison

Enum constants can be compared using == and equals(), since they are singleton instances.

Example:

public class EnumComparisonExample {
    public enum Size {
        SMALL, MEDIUM, LARGE
    }

    public static void main(String[] args) {
        Size size1 = Size.MEDIUM;
        Size size2 = Size.MEDIUM;
        Size size3 = Size.LARGE;

        // Comparing enums using ==
        System.out.println(size1 == size2);  // true
        System.out.println(size1 == size3);  // false

        // Comparing enums using equals()
        System.out.println(size1.equals(size2));  // true
        System.out.println(size1.equals(size3));  // false
    }
}

Explanation:

Enums are compared using == because they are effectively singletons, meaning each constant is a single instance.

Output:

true
false
true
false

Conclusion

Java enums are more than just collections of constants. They are full-featured objects that can have fields, methods, and even constructors.

They are often used for defining a fixed set of constants, but their ability to implement interfaces, have methods, and work with switch statements makes them powerful tools for building robust and readable code.

In this tutorial, we covered:

Basic enum definition and usage.
Using enums in switch statements.
Enums with fields, methods, and constructors.
Overriding methods in enums.
Built-in enum methods (values(), valueOf(), ordinal()).
Enum comparison and enums implementing interfaces.

With this knowledge, you can leverage enums to make your Java applications more efficient and type-safe.

You may also like