Java Enums

Java Enums: A Complete Guide with Examples and Exercises

Enums, short for “enumerations,” in Java represent a fixed set of constant values. Enums are a special type of class introduced in Java 5 that can have fields, methods, and constructors. They provide a clean and organized way to handle fixed sets of data, like days of the week, seasons, or directions.

In this guide, we’ll cover the fundamentals of Java enums, explain why they’re useful, and provide exercises to solidify your understanding.


Table of Contents

  1. What is an Enum?
  2. Declaring and Using Enums
  3. Enum Fields, Methods, and Constructors
  4. Enum Methods (values(), valueOf(), ordinal())
  5. Enum in Switch Statements
  6. Advanced Enum Usage
  7. Exercises

1. What is an Enum?

An enum (enumeration) is a special Java type used to define collections of constants. Unlike traditional constants, enums are more robust, type-safe, and provide a structured way to represent and use fixed sets of related values.

Example of Basic Enum

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

Here, Day is an enum that defines a set of constants representing the days of the week.

2. Declaring and Using Enums

To declare an enum, use the enum keyword. Enums can be used in many of the same ways as classes, such as being assigned to variables, being used in conditionals, and being passed as parameters.

Example of Declaring and Using Enums

enum Level {
    LOW, MEDIUM, HIGH;
}

public class Main {
    public static void main(String[] args) {
        Level myLevel = Level.MEDIUM;

        if (myLevel == Level.HIGH) {
            System.out.println("High level");
        } else {
            System.out.println("Not high level");
        }
    }
}

In this example:

  • Level is an enum with three constants: LOW, MEDIUM, and HIGH.
  • The myLevel variable holds the value Level.MEDIUM, and we check it in a conditional statement.

3. Enum Fields, Methods, and Constructors

Enums can have fields, methods, and constructors to provide more functionality. The constructor for an enum is private and is automatically called when each constant is created. Enum fields can store additional information about each constant, while methods allow for custom behavior.

Example with Enum Fields, Constructor, and Method

enum Size {
    SMALL(30), MEDIUM(40), LARGE(50);

    private int volume;  // Field for storing volume

    Size(int volume) {   // Constructor
        this.volume = volume;
    }

    public int getVolume() {  // Method to access volume
        return volume;
    }
}

public class Main {
    public static void main(String[] args) {
        Size size = Size.MEDIUM;
        System.out.println("Size: " + size + ", Volume: " + size.getVolume());
    }
}

In this example:

  • Size has a volume field and a constructor to initialize it.
  • Each enum constant (SMALL, MEDIUM, LARGE) is associated with a specific volume value.
  • getVolume returns the volume of the specific enum constant.

4. Enum Methods (values(), valueOf(), ordinal())

Java provides several built-in methods for working with enums:

  • values(): Returns an array of all enum constants in the order they were declared.
  • valueOf(String name): Returns the enum constant with the specified name.
  • ordinal(): Returns the position of the enum constant in its declaration.

Example of Using Enum Methods

enum Color {
    RED, GREEN, BLUE;
}

public class Main {
    public static void main(String[] args) {
        // values() method
        for (Color color : Color.values()) {
            System.out.println(color);
        }

        // valueOf() method
        Color myColor = Color.valueOf("GREEN");
        System.out.println("My Color: " + myColor);

        // ordinal() method
        System.out.println("Position of GREEN: " + Color.GREEN.ordinal());
    }
}

Here:

  • Color.values() returns an array of all Color enum constants.
  • Color.valueOf("GREEN") retrieves the GREEN constant.
  • Color.GREEN.ordinal() returns 1, the position of GREEN (0-based indexing).

5. Enum in Switch Statements

Enums can be used directly in switch statements, making them easy to work with when you need to execute different code based on an enum value.

Example with Enum in Switch Statement

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

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

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

In this example, different messages are printed depending on the value of the today variable, which holds a Day enum constant.

6. Advanced Enum Usage

Enums can implement interfaces, allowing them to define custom behavior for each constant. This makes enums powerful for cases where each constant needs a unique implementation of a method.

Example of Enum Implementing an Interface

interface Operation {
    int apply(int x, int y);
}

enum Calculator implements Operation {
    ADD {
        @Override
        public int apply(int x, int y) {
            return x + y;
        }
    },
    SUBTRACT {
        @Override
        public int apply(int x, int y) {
            return x - y;
        }
    },
    MULTIPLY {
        @Override
        public int apply(int x, int y) {
            return x * y;
        }
    },
    DIVIDE {
        @Override
        public int apply(int x, int y) {
            return x / y;
        }
    }
}

public class Main {
    public static void main(String[] args) {
        int result = Calculator.ADD.apply(5, 3);
        System.out.println("Addition Result: " + result);

        result = Calculator.MULTIPLY.apply(5, 3);
        System.out.println("Multiplication Result: " + result);
    }
}

Here, each constant in the Calculator enum implements the apply method from the Operation interface, providing a unique behavior for each mathematical operation.

7. Exercises

Exercise 1: Define an Enum with Fields and Methods

Create an enum Planet that includes:

  1. Enum constants for MERCURY, VENUS, EARTH, and MARS.
  2. A field mass and a field radius for each planet.
  3. A constructor to initialize mass and radius.
  4. A method surfaceGravity() to calculate surface gravity.

Use this formula for gravity: gravity = mass / (radius * radius).

In the main method, print the gravity of each planet.

Exercise 2: Enum in a Switch Statement

Create an enum TrafficLight with constants RED, YELLOW, and GREEN. Use a switch statement to print different messages based on the traffic light color. For example, “Stop” for RED, “Ready” for YELLOW, and “Go” for GREEN.

Exercise 3: Enum Implementing an Interface

  1. Create an interface SeasonBehavior with a method activity().
  2. Create an enum Season with constants SUMMER, WINTER, SPRING, and AUTUMN, each implementing the activity() method.
  3. Print the activity for each season by calling activity() on each constant in the main method.

Sample Solution for Exercise 1

enum Planet {
    MERCURY(3.30e+23, 2.4397e6),
    VENUS(4.87e+24, 6.0518e6),
    EARTH(5.97e+24, 6.371e6),
    MARS(6.42e+23, 3.3895e6);

    private final double mass;   // in kilograms
    private final double radius; // in meters

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

    public double surfaceGravity() {
        return mass / (radius * radius);
    }
}

public class Main {
    public static void main(String[] args) {
        for (Planet planet : Planet.values()) {
            System.out.printf("Gravity on %s: %f%n", planet, planet.surfaceGravity());
        }
    }
}

Sample Solution for Exercise 2

enum TrafficLight {
    RED, YELLOW, GREEN;
}

public class Main {
    public static void main(String[] args) {
        TrafficLight light = TrafficLight.RED;

        switch (light) {
            case RED:
                System.out.println("

Stop");
                break;
            case YELLOW:
                System.out.println("Ready");
                break;
            case GREEN:
                System.out.println("Go");
                break;
        }
    }
}

Sample Solution for Exercise 3

interface SeasonBehavior {
    void activity();
}

enum Season implements SeasonBehavior {
    SUMMER {
        @Override
        public void activity() {
            System.out.println("Going to the beach");
        }
    },
    WINTER {
        @Override
        public void activity() {
            System.out.println("Skiing");
        }
    },
    SPRING {
        @Override
        public void activity() {
            System.out.println("Gardening");
        }
    },
    AUTUMN {
        @Override
        public void activity() {
            System.out.println("Hiking");
        }
    }
}

public class Main {
    public static void main(String[] args) {
        for (Season season : Season.values()) {
            System.out.print(season + ": ");
            season.activity();
        }
    }
}

Conclusion

Java enums offer a powerful way to work with constant values, providing flexibility through fields, methods, and constructors. They also enable complex behaviors when implementing interfaces or using them with switch statements. Practice these exercises to deepen your understanding of Java enums and their usage.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top