How to use Enums in java

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

1. Overview of Enum

Enum is a java type/class which holds a fixed set of related constants, it is the replacement of the traditional definition of multiple static final variables in java. It is mostly recommended when you define a method which accepts a constant argument, this way you force the method callers to commit to the predefined constants and prevent them to pass random constant values.

2. A typical Enum

The above enum can be represented traditionally as:

some points to consider when defining an enum:

  1. Enum implicitly extends java.lang.Enum, so it can’t extend other class.
  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 instance of Enum using new operator, 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.

3. Common operations of Enum

Following are common operations of Enum:

3.1 Instantiate Enum

Output:

 

3.2 Convert String to Enum

Output:

 

3.3 Compare enums

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

Output:

 

3.4 Iterate over Enum values

Output:

 

3.5 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:

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

Output:

That’s it !!

 

husseinterek

Founder of programmergate.com, I have a passion in software engineering and everything related to java environment.

You may also like...

Leave a Reply

Be the First to Comment!

avatar