DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Related

  • Advanced Java Garbage Collection Concepts: Weak References, Finalization, and Memory Leaks
  • Distributed Rate Limiting in Java: A Deep Dive into Bucket4j + PostgreSQL
  • From Java 8 to Java 21: How the Evolution Changed My Developer Workflow
  • Effective Exception Handling in Java and Spring Boot Applications

Trending

  • Debunking LLM Intelligence: What's Really Happening Under the Hood?
  • Want to Become a Senior Software Engineer? Do These Things
  • AI Agent Architectures: Patterns, Applications, and Implementation Guide
  • Top Trends for Data Streaming With Apache Kafka and Flink
  1. DZone
  2. Coding
  3. Java
  4. Using Enums in Java [Snippets]

Using Enums in Java [Snippets]

This quick primer on enums in Java will go through some typical use cases and operations using snippets of enums in action.

By 
Hussein Terek user avatar
Hussein Terek
·
Mar. 07, 18 · Code Snippet
Likes (7)
Comment
Save
Tweet
Share
34.2K Views

Join the DZone community and get the full member experience.

Join For Free

In this article, we provide several examples of the usage of Enums in Java.

Enum Overview

Enum is a Java type/class that holds a fixed set of related constants. It is a replacement for the traditional definition of multiple static final variables in Java. It is mostly recommended when you define a method that accepts a constant argument. This way you force the method callers to commit to the predefined constants and prevent them from passing random constant values.

A Typical Enum

public enum ErrorCodes {
    BUSINESS_ERROR(100), SERVER_ERROR(500), NETWORK_ERROR(1000);

    private int errorCode;

    private ErrorCodes(int errorCode) {
    this.errorCode = errorCode;
    }

    public int getErrorCode() {
    return errorCode;
    }
}


The above enum can be represented traditionally as:

public static final int BUSINESS_ERROR = 100;
public static final int SERVER_ERROR = 500;
public static final int NETWORK_ERROR = 1000;


Some points to consider when defining an enum:

  1. Enum implicitly extends java.lang.Enum, so it can't extend other classes.
  2. Enum constructors can never be invoked in the code — they are always called automatically when an enum is initialized.
  3. You can't create an instance of Enum using new operators. It should have a private constructor and is normally initialized as: ErrorCodes error = ErrorCodes.BUSSINESS_ERROR
  4. Each constant in the enum has only one reference, which is created when it is first called or referenced in the code.

Common Operations of Enum

The following are common operations of Enum:

Instantiate Enum

private static void instantiateEnum() {
    ErrorCodes businessError = ErrorCodes.BUSINESS_ERROR;
    System.out.println(businessError);
}


Output:

BUSINESS_ERROR

 

Convert String to Enum

private static void convertStringToEnum() {
    ErrorCodes businessError = ErrorCodes.valueOf("BUSINESS_ERROR");
    System.out.println(businessError);
    System.out.println(businessError.getErrorCode());
}


Output:

BUSINESS_ERROR
100

 

Compare Enums

To compare enums, you can use: ==, equals() or switch() block.

private static void checkEnumForEquality() {
    ErrorCodes businessError = ErrorCodes.BUSINESS_ERROR;

    if(businessError == ErrorCodes.BUSINESS_ERROR)
    {
    System.out.println("You can check enum for equality using == operator.");
    }

    if(businessError.equals(ErrorCodes.BUSINESS_ERROR))
    {
    System.out.println("You can check enum for equality using equals() method.");
    }

    switch(businessError)
    {
        case BUSINESS_ERROR: 
        {
            System.out.println("You can check enum for equality using switch block.");
            break;
        }
        default: System.out.println("Non-business error.");
    }
}


Output:

You can check enum for equality using == operator.
You can check enum for equality using equals() method.
You can check enum for equality using switch block.

 

Iterate over Enum values

private static void iterateEnumValues() {
    System.out.println("Iterating over ErrorCodes enum");
    for(ErrorCodes errorCode : ErrorCodes.values())
    {
        System.out.println("Enum key = " + errorCode);
        System.out.println("Enum value = " + errorCode.getErrorCode());
    }
}


Output:

Iterating over ErrorCodes enum
Enum key = BUSINESS_ERROR
Enum value = 100
Enum key = SERVER_ERROR
Enum value = 500
Enum key = NETWORK_ERROR
Enum value = 1000

 

Retrieve Enum by Value

By default, Java doesn't provide any way to retrieve an Enum instance by its value. To do so, update ErrorCodes enum in order to expose a hashmap, which maps each value to its corresponding Enum instance. The hashmap is filled and exposed as the following:

public enum ErrorCodes {
    BUSINESS_ERROR(100), SERVER_ERROR(500), NETWORK_ERROR(1000);

    private int errorCode;
    private static Map<Integer, ErrorCodes> errorCodeByErrorNumber = new HashMap<Integer, ErrorCodes>();

    static {
        for (ErrorCodes errorCode : ErrorCodes.values()) {
        errorCodeByErrorNumber.put(errorCode.getErrorCode(), errorCode);
        }
    }

    private ErrorCodes(int errorCode) {
    this.errorCode = errorCode;
    }

    public int getErrorCode() {
    return errorCode;
    }

    public static ErrorCodes getErrorCodeByNumber(Integer errorNumber) {
    return errorCodeByErrorNumber.get(errorNumber);
    }
}


Now, you can retrieve an enum instance of a numeric value as the following:

private static void retrieveEnumByValue() {
    ErrorCodes businessError = ErrorCodes.getErrorCodeByNumber(100);
    System.out.println(businessError);
}


Output:

BUSINESS_ERROR


That's it!

Java (programming language)

Published at DZone with permission of Hussein Terek, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Advanced Java Garbage Collection Concepts: Weak References, Finalization, and Memory Leaks
  • Distributed Rate Limiting in Java: A Deep Dive into Bucket4j + PostgreSQL
  • From Java 8 to Java 21: How the Evolution Changed My Developer Workflow
  • Effective Exception Handling in Java and Spring Boot Applications

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: