Java Enumeration Tutorial and Example

This post is all about Java Enumeration Tutorial. Java Enumeration or java enum act like a constant variable with additional functionality.

For example, you may want to create a constant for gender. If you don’t know how to use enum, probably you will just define an integer constant for male and female values:

public static final int MALE = 1;
public static final int FEMALE = 2;

With enum, you can define it like this:

public enum Gender {
    MALE, FEMALE
}

That’s the very basic creation of enum. You can now use it just as how you use a constant variable. But what if you want to add property to the enum such as integer so that you can save the value in database? Enum can have constructor where you can define the property:

public enum Gender {
    MALE(1), FEMALE(2);

    private int code;
    
    Gender(int code) {
        this.code = code;
    }

    public int getCode() {
        return code;
    }
}


In the above code, we define the constructor to take an integer parameter. We define the argument in our declaration of enum eg. 1 for MALE and 2 for FEMALE. Take note of the semicolon after FEMALE(2):

FEMALE(2);

It is necessary to add semicolon after the declarations of the enum if you have more codes after the declarations.

Now what if you want to get an instance of the enum based on the code? One implementation could be like this:

public enum Gender {
    MALE(1), FEMALE(2);

    private int code;
    private static Map genderMap;

    Gender(int code) {
        this.code = code;
    }

    public int getCode() {
        return code;
    }

    public static Gender getGender(int code) {
        if (genderMap == null) {
            genderMap = new HashMap();
            genderMap.put(1, Gender.MALE);
            genderMap.put(2, Gender.FEMALE);
        }
        return genderMap.get(code);
    }
}

Take note that we make it static method and field. Consider Java Enumeration as a class that also act like a constant. Below is an example of java enumeration usage.
Person.java

public class Person {
    private Gender gender;

    public Gender getGender() {
        return gender;
    }

    public void setGender(Gender gender) {
        this.gender = gender;
    }
}

Main method:

public static void main(String[] args) {
        Person person1 = new Person();
        person1.setGender(Gender.MALE);

        Person person2 = new Person();
        person2.setGender(Gender.FEMALE);

        System.out.println("First Person Gender: " + person1.getGender() + ", code = " + person1.getGender().getCode());
        System.out.println("Second Person Gender: " + person2.getGender() + ", code = " + person2.getGender().getCode());
    }

The output will be:
java-enum-example

Share this tutorial!