Java Enums Complete Tutorial

In this section we will learn what the enums are and how to use them in Java.

What is enum in java?

The `enum` is a special class that represents a list of static constant objects of its type.

We say an enum is a special class; this means we can add attributes and methods (basically members that we can use inside a class) inside the body of an enum as well.

Static means in order to access the members of an enum class (its values (AKA objects)), we need to use the name of that class.

Constant means: the objects (values) in an enum will stay with that enum for as long as the program is alive. We can’t remove them from an enum.

How to create enums in Java? (Enum syntax)

Look at this example:

enum Color{
    BLACK, RED, BLUE;
}

 

Here the name of the enum is `Color` and its constant values (objects) are `BLACK`, `RED` and `BLUE` and all of these values are basically objects of type Color.

`enum` keyword: in order to create an enum list, we start with the keyword `enum`.

After the keyword `enum` we set the name of the enum(in the example above it was `Color`) and after that we declare the list of constant values (objects) in the body of the enum.

Example: Java enum

enum Color{
    BLACK, RED("Jack"), BLUE;
    private String name;
    Color(){}
    Color(String name){
        this.name = name;
    }
    
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

 

Java Enum constructors

We mentioned that Enums are class, right? So they can have constructors as well.

Here the `Color` enum has two constructors, one takes no argument, and the other takes one string value that will be assigned to the private `name` variable, which is the member of the `Color` enum.

Also, this enum has two methods to get and set the value of the `name` variable.

Note: because there was a constructor in this enum that takes string value, the compiler use that constructor to initialize the constant object `RED` (because it took a string value at the initialization time). Also, because the other two constant objects `BLACK` and `BLUE` didn’t took any argument at their initialization, behind the scene the compiler used the other constructor (the empty one) to initialize them.

Java enum constructor Note:

You should know that the constructor that we create inside the body of an enum will be only used by the compiler just to initialize the constant objects that we declare inside the body of the enum. So we can’t use these constructors outside of the enum to create an object of that enum type.

How to use Java enums in a program?

We mentioned that enums are static! That means in order to access the objects inside such class, we need to use the name of the enum + dot `.` + the name of the target object.

Note: before running an example, we should know that an enum can be defined inside and outside of a class.

Example: using Java enums in a program

enum Color{
    BLACK, RED("Bright Red"), BLUE;
    private String name;
    Color(){}
    Color(String name){
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
public class Simple {

    public static void main(String[] args) {
        Color clr = Color.RED;
        System.out.println(clr.getName());
    }
}

 

Output: Bright Red

Notes:

  1. Constant values that are declared inside the body of an enum are objects of type the enum itself and they are initialized automatically behind the scene by the compiler.
  2. These values (objects) are static. This means we can use the name of the enum to access these values (objects).

In the body of the `main()` method, we’ve created `clr` variable which is of type `Color` enum and then assigned the value (object) RED to this variable.

Basically, the `clr` has a reference to the RED object now.

In the next line, we called the `getName()` method of the RED value (object) to get the value set for the `name` member (private variable) of the object and as you can see the value `Bright Red` is sent to the output stream.

Java Enum Class

An enum type inherits from a class named `Enum`. Inside this class, there are a couple of methods that constant objects of an enum type can use.

Two of these methods are `ordinal()` and `name()` methods.

  • `ordinal()`: this method returns the position of the constant value (object) in the list of values in the enum.

Note: the first constant value is positioned at zero, the second one is positioned 1 and so on.

  • `name()`: this method returns a string representation of the name of the constant value (object).

Example: using Java Enum ordinal() and name() methods

enum Color{
    BLACK, RED("Bright Red"), BLUE;
    private String name;
    Color(){}
    Color(String name){
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
public class Simple {

    public static void main(String[] args) {
        Color clr = Color.RED;
        System.out.println(clr.getName());
        System.out.println("The position is: "+clr.ordinal());
        System.out.println("The name is: "+clr.name());

    }
}

 

Output:

Bright Red

The position is: 1

The name is: RED

Java Enum and for loop and values() method

When we want to loop through the entire constant values of an enum, we can use a method named `values()` and as a result, it’ll return an array of all the constant values in that enum.

Example: enum and for loop in Java

enum Color{
    BLACK, RED("Bright Red"), BLUE;
    private String name;
    Color(){}
    Color(String name){
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
public class Simple {

    public static void main(String[] args) {
        for (Color clr: Color.values()){
            System.out.println(clr.name());
        }
    }
}

 

Output:

BLACK

RED

BLUE

 

String to enum in Java: Enum valueof() method

This method takes a string as its argument and an enum can use this method to return a reference of one of its constant values that matches the string argument.

Example: using Enum valueof() method

enum Color{
    BLACK, RED("Bright Red"), BLUE;
    private String name;
    Color(){}
    Color(String name){
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
public class Simple {

    public static void main(String[] args) {
        Color clr = Color.valueOf("BLUE");
        System.out.println(clr.name());
    }
}

 

Output:

BLUE

 

Example: Java Enum and switch statement

enum Color{
    BLACK, RED("Bright Red"), BLUE;
    private String name;
    Color(){}
    Color(String name){
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
public class Simple {

    public static void main(String[] args) {
        Color clr = Color.valueOf("BLUE");
        switch (clr){
            case BLACK:
                System.out.println("The value is black");
                break;
            case RED:
                System.out.println("The value is red");
                break;
            case BLUE:
                System.out.println("The value is blue");
                break;
            default:
                System.out.println("Unknown value");
        }
    }
}

 

Output: The value is blue

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies