Overview of Enums in Java

In Java, an Enum (which is short for enumeration) is a special data type developers can use to define a set of named constants. Every constant that is part of an Enum is considered an instance of the Enum type and has its own unique name. Enums were introduced way back in Java 5 and, since then, have become a vital part of the Java programming language. Enums provide programmers a simple way to define a fixed set of values ​​that can then be referenced in your code. We learn more about enums in this programming tutorial.

Benefits of Enums in Java

One of the most important benefits of Enums in Java is the fact that they help make your code more readable and less prone to errors and exceptions. Enums give us a way to define a set of related values ​​we can use throughout our codebase. This eliminates (or lessens) the need to worry about typos or human errors when working with these data types. Additionally, enums are type-safe, which means that the compiler will catch mistakes at compilation time, making debugging a much easier process.

You can learn more about exception handling in our tutorial: Java exception handling.

Enum syntax in Java

The syntax for defining an enum in Java can be seen in the code example below:

enum EnumName { CONSTANT1, CONSTANT2, CONSTANT3, … }

Note that every constant defined in the Enum set needs to be separated by a comma. Here is a simplified example of defining an enum:

enum Direction { UP, DOWN, LEFT, RIGHT }

In the above code example, we defined an Enum named Direction, which contained four constants – UP, DOWN, LEFT, and RIGHT.

How to Use Enums in Java

Now that know how to define an Enum, we can use it in our code, the same as any other data type. Below are several code examples demonstrating how to use Enums in Java, including:

    • Using enums in switch statements
    • How to loop through enums
    • How to add methods to enums

Java Switch Statement and Enums

One particularly common way developers use Enums in Java is inside of a switch statement, as show in the following code sample:

Direction d = Direction.UP; switch (d) { case UP: System.out.println(“Turning Up”); break; case DOWN: System.out.println(“Turning Down”); break; case LEFT: System.out.println(“Turning Left”); break; case RIGHT: System.out.println(“Turning Right”); break; }

In our Java switch example above, we defined a variable named d that had the type Direction. We then set its initial value to Direction.UP. If we need to know the current value of our variable d, we can call the switch statement, which then prints a message using the value found in our Enum.

Reading: Introduction to Java Primitive Data Types

How to Loop Through an Enum

It is also possible to loop through the constants in an Enum using a for loop in Java. Here is an example of how to use a for loop for Enum iteration:

for (Direction d : Direction.values()) { System.out.println(d); }

In the above code, we used the values() method in order to retrieve an array of every constant that resides in our Direction Enum. Then we loop through the array, printing out each constant we find in the list courtesy of System.out.println().

How to Add Methods to an Enum in Java

Java Enums are a powerful tool that are capable of much more than simply defining sets of constants. For instance, let’s say we wanted to add a method to our Enum. We could do say with the following code snippet:

enum Direction { UP(“Turning Up”), DOWN(“Turning Down”), LEFT(“Turning Left”), RIGHT(“Turning Right”); private final String description; Direction(String description) { this.description = description; } public String getDescription() { return description; } }

Here, we have added a method named getDescription() to our Direction Enum. Every constant in our Enum will now have a description field that gets set when the constant is defined (represented by the values ​​in parentheses). The getDescription() method then returns the description found for the given constant in our Enum.

Java enums with parameters

Enums in Java may also contain parameters, similar to constructors in classes. For instance, if we have a dataset representing the planets in our solar system, we might have parameters for the mass and radius for each entry. We could define the dataset in the following manner:

enum Planets { MercuryPlanet(3.303e+23, 2.4397e6), VenusPlanet(4.869e+24, 6.0518e6), EarthPlanet(5.976e+24, 6.37814e6), MarsPlanet(6.421e+23, 3.3972e6), JupiterPlanet(1.9 e+27, 7.1492e7), SaturnPlanet(5.688e+26, 6.0268e7), UranusPlanet(8.686e+25, 2.5559e7), NeptunePlanet(1.024e+26, 2.4746e7); private final double mass; private final double radius; private final double surfaceGravity; private static final double G = 6.67300E-11; Planets(double mass, double radius) { this.mass = mass; this.radius = radius; this.surfaceGravity = G * mass / (radius * radius); } public double getMass() { return mass; } public double getRadius() { return radius; } public double getSurfaceGravity() { return surfaceGravity; } public double getSurfaceWeight(double otherMass) { return otherMass * surfaceGravity; } }

Above, we have defined an Enum named Planets that contains eight constants, each representing a planet in our solar system. Each constant has a mass and radius parameter, which are used to calculate the surfaceGravity of the given planet. We also added a getSurfaceWeight() method, which takes a double parameter that represents the mass of an object and then returns the surface weight of that object on the planet in question.

Final Thoughts on Java Enums

Enums are, without a doubt, a powerful feature in Java that lets developers define a set of named constants for later reference in their programs. Enums make code more readable, efficient, and less error prone. They can be used in a variety of ways, including as constant definitions, in loops, in switch statements, and much more.

read more Java programming tutorials and guides to software development.

Related posts

Teamwork Project Management Review


Active Collaboration Project Management Review




Leave a Comment