Java Enum: An Introduction to the Java Enum Class

Athena Ozanich
Athena Ozanich

Published:

Java provides many classes and datatypes for use in software development that offer increased flexibility and power. One such tool is called the enum type class, and it provides the ability to create defined constants that provide more control over the software you make and how users can interact with it.

Below are some jump links to help simplify navigating this post.

Without any further delay, let's jump right in.

Download Now: Free HTML & CSS Hacks

What is Enum in Java?

A Java Enum is a Java type-class used to define collections of constants for your software according to your own needs. Each item in a Java enum is called a constant, an immutable variable — a value that cannot be changed. Constants are frequently used to help define operation parameters and guidelines for a piece of software or user.

Creating an enum is a simple task and does not require much discussion. Declaring an enum is done using standard syntax and looks a lot like declaring Java classes. The only real difference is that it uses a unique keyword reserved specifically for enums and they are type-safe objects. Type-safe objects are checked at compile time for type conformity, and

 
public enum AuthLvl {
    ADMIN,
    USER,
    UNAUTHORIZED
}

The code above could be used to create an enum that sets the user's authorization level upon login. To access the constant, you would simply call it like a class type such as String or int then assign it to a variable which would then be attached to the user. Let's look at the syntax for accessing and assigning one of the above constants to a user.

 
AuthLvl userLvl = AuthLvl.ADMIN;

The variable named userLvl will have a type that is the same name of the declared enum type, its value will be one of the constants. In this example, the userLvl is set to the value of ADMIN, which is accessed as a property of the AuthLvl type-class.

How to Set Enum Value in Java

The great thing about a Java Enum is that constants can also have values in addition to their name. For example, specific permissions can be added as a value for an ADMIN level user, such as giving them write permissions.

Let's see what the code looks like using our example of user authentication and permissions.

 
public enum Auth {
    ADMIN("Write");
    public final String permission;
    private Auth(String permission) {
        this.permission = permission;
    }
}

A new string value of “Write” is added to the ADMIN constant in the above code. This is a great step in the right direction, but you still don't have a way to access that value. To ensure access is available, Java requires the value to be assigned as a final which is another type of constant.

 
public final String permission;

From there you can take it a step further, and give that value a name. Naming the value allows multiple ways to access it so that it’s even easier to target when needed. To name an enum constant’s value, you will assign it to the this value of the enum. You can complete this process multiple times to create and add values to the enum constants as you see fit.

 
private Auth(String permission) {
   this.permission = permission;
}

So far, you’ve declared the enum and a named constant a value for it, thus expanding on its use. Furthermore, at this point, you’ve even given a label for the value by assigning it to this attribute of the enum. The benefit of this is that you can retrieve the value by name using the dot notation. The following code snippet shows how to target this value and print it to the console.

This labeling further extends the functionality of the enum and its constants, making them flexible and robust.

Next, let’s look at the ways we can incorporate this enum into our code.

How to Use Enum in Java

The primary use of the enum is to compare, much like our example of a simple auth enum. Using it you can compare a user's authorization level with their respective permissions. The comparative operations can be used in if blocks, switch statements, functions, loops, etc.

Let's look at a couple of examples of these uses, and see how to perform these comparisons.

 
String[] currUser = {"John Smith", "Write"};
if(Auth.ADMIN.permission == currUser[1]){
   System.out.println(true);
}

This setup written within the main class will check the current user's authorization level and permissions, then perform a designated action. This could serve to validate a user's permission to perform certain actions within a piece of software, such as editing information.

Now that you’ve seen how it can be used to make comparisons, let’s look at a practical use case of the enum within a switch statement.

Java Enum Example

One of the most practical ways to use an enum for comparative validation is to combine it with a switch statement. Switch statements provide a way to create explicit controls for your software’s operational parameters. Combined with the benefits of enum constants, setting control parameters becomes a simpler task.

The video below illuminates how to set up an enum with a switch statement.

Let’s look at a code snippet combining the Auth enum with a switch statement.

 
String[] currUser = {"John Smith", Auth.USER.toString()};        
switch (currUser[1]) {
   case "ADMIN":
      Auth level = Auth.ADMIN;
      System.out.println("You have logged in as an Administrator ");
   break;
   case "USER":
      Auth level = Auth.ADMIN;
      System.out.println(Auth.USER);
   break;
   case "UNAUTHORIZED":
      Auth level = Auth.ADMIN;  
      System.out.println(Auth.UNAUTHORIZED);
   break;
}

Note the use of the toString() method which converts the constant to a Java string for use in the currUser array. The switch statement compares the string for each case, if the provided case matches, it will perform an action. This switch statement sets the current user level based on the second value in the currUser array.

In this example, if the case matches, the equivalent enum constant gets assigned to an Auth type variable called level. The current user session is then used to define the operating parameters and permissions for the user.

Getting Started With Using Java Enum in Your Software

The Java enum is a powerful tool that can be used to perform a multitude of actions, set controls, parameters, and more. Knowing how to identify when they will be most useful will come mostly with practice. There is a good rule of thumb, which is to consider if a value can only have one of a specific set of immutable values.

New Call-to-action

Topics: Java

Related Articles

We're committed to your privacy. HubSpot uses the information you provide to us to contact you about our relevant content, products, and services. You may unsubscribe from these communications at any time. For more information, check out our Privacy Policy.

Learn more about HTML and CSS and how to use them to improve your website.