Java - Enums: A Beginner's Guide

Hello there, aspiring Java programmers! Today, we're going to dive into the wonderful world of Java Enums. Don't worry if you've never heard of them before – by the end of this tutorial, you'll be an Enum expert! So, grab a cup of your favorite beverage, and let's get started!

Java - Enums

Introduction to Enums

Have you ever found yourself in a situation where you needed to represent a fixed set of constants in your code? Maybe you were creating a program for a coffee shop and needed to represent different sizes of coffee cups. Or perhaps you were building a game and needed to represent the different directions a character could move. This is where Enums come to the rescue!

An Enum, short for "enumeration," is a special type of class in Java that represents a group of constants (unchangeable variables, like final variables). Think of it as a fancy way to create a set of predefined values that don't change.

Class Declaration

Let's start by looking at how we declare an Enum. The syntax is quite simple:

enum CoffeeSize {
    SMALL,
    MEDIUM,
    LARGE
}

In this example, we've created an Enum called CoffeeSize with three constants: SMALL, MEDIUM, and LARGE. Notice how we use the enum keyword instead of class, and how each constant is separated by a comma.

Class Constructors

Enums can have constructors, just like regular classes. This allows us to associate additional data with each enum constant. Let's expand our CoffeeSize example:

enum CoffeeSize {
    SMALL(8),
    MEDIUM(12),
    LARGE(16);

    private final int ounces;

    CoffeeSize(int ounces) {
        this.ounces = ounces;
    }

    public int getOunces() {
        return ounces;
    }
}

In this updated version, we've added a constructor that takes an int parameter representing the number of ounces for each size. We've also added a private field ounces and a getter method getOunces().

Class Methods

Enums can have methods just like regular classes. Let's add a method to our CoffeeSize enum:

enum CoffeeSize {
    SMALL(8),
    MEDIUM(12),
    LARGE(16);

    private final int ounces;

    CoffeeSize(int ounces) {
        this.ounces = ounces;
    }

    public int getOunces() {
        return ounces;
    }

    public String getDescription() {
        return this.name() + " coffee (" + this.ounces + " oz)";
    }
}

We've added a getDescription() method that returns a string describing the coffee size. The name() method is inherited from the Enum class and returns the name of the constant as a string.

Methods Inherited

All enums implicitly inherit from java.lang.Enum. This means they come with some built-in methods. Here are some of the most commonly used ones:

Method Description
name() Returns the name of the enum constant
ordinal() Returns the position of the enum constant (0-based)
valueOf(String name) Returns the enum constant with the specified name
values() Returns an array containing all of the enum constants

Example

Now, let's put everything together in a complete example:

public class CoffeeShop {
    public static void main(String[] args) {
        CoffeeSize mySize = CoffeeSize.MEDIUM;

        System.out.println("I ordered a " + mySize.getDescription());
        System.out.println("This size has an ordinal value of: " + mySize.ordinal());

        System.out.println("\nAll available sizes:");
        for (CoffeeSize size : CoffeeSize.values()) {
            System.out.println(size.getDescription());
        }

        // Using valueOf
        CoffeeSize anotherSize = CoffeeSize.valueOf("LARGE");
        System.out.println("\nUsing valueOf: " + anotherSize.getDescription());
    }
}

enum CoffeeSize {
    SMALL(8),
    MEDIUM(12),
    LARGE(16);

    private final int ounces;

    CoffeeSize(int ounces) {
        this.ounces = ounces;
    }

    public int getOunces() {
        return ounces;
    }

    public String getDescription() {
        return this.name() + " coffee (" + this.ounces + " oz)";
    }
}

Output

When you run this program, you'll see the following output:

I ordered a MEDIUM coffee (12 oz)
This size has an ordinal value of: 1

All available sizes:
SMALL coffee (8 oz)
MEDIUM coffee (12 oz)
LARGE coffee (16 oz)

Using valueOf: LARGE coffee (16 oz)

Let's break down what's happening in this example:

  1. We create a CoffeeSize variable mySize and set it to MEDIUM.
  2. We print the description of mySize using the getDescription() method.
  3. We print the ordinal value of MEDIUM, which is 1 (remember, ordinal values start at 0).
  4. We use a for-each loop to iterate through all the CoffeeSize values and print their descriptions.
  5. Finally, we demonstrate the use of valueOf() to get the LARGE enum constant by its name.

And there you have it! You've just taken your first steps into the world of Java Enums. They're a powerful tool for representing fixed sets of constants in a type-safe way.

Remember, Enums are more than just glorified constants. They can have constructors, fields, and methods, making them incredibly versatile. They're perfect for representing things like days of the week, card suits, pizza sizes, or any other set of fixed values in your programs.

As you continue your Java journey, you'll find many more uses for Enums. They're a fundamental part of the Java language, and mastering them will make you a more effective and efficient programmer.

Keep practicing, keep coding, and most importantly, keep enjoying the process of learning. Before you know it, you'll be writing complex Java programs with ease. Happy coding!

Credits: Image by storyset