Java
Enum
Programming
Java Enum
Software Development

Java Enum definition

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Java Enums are a special data type introduced in Java 1.5 as part of the Java language enhancement known as Java SE 5. They provide a way to define a collection of named constants, which can be used for predefined values. This feature facilitates code clarity and makes it easier to handle groups of related constants.

Overview of Java Enum

Enums are defined using the enum keyword in Java. By default, an enum is a subclass of the java.lang.Enum class and thus comes with a set of standard methods such as name(), ordinal(), and values(). Enums are inherently static and final, meaning they can’t be instantiated or subclassed.

Basic Enum Declaration

Here is a simple example to demonstrate how an enum is defined:

java
public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

In this example, Day is an enum type with seven named constants. These constants are enumerated, meaning each one has an associated ordinal value starting at zero (SUNDAY has an ordinal of 0, MONDAY has an ordinal of 1, and so on).

Enum Methods

Enums come with several methods:

  • ordinal(): Returns the ordinal position of the enum constant.
  • name(): Returns the name of the enum constant, exactly as declared in its enum declaration.
  • values(): Returns an array containing all the enum values in the order they are declared.

Example usage:

java
for (Day day : Day.values()) {
    System.out.println(day + " has an ordinal value of " + day.ordinal());
}

Enum with Fields, Constructors, and Methods

Enums can have fields, constructors, and methods just like regular classes. This allows enums to associate data with constants and provide methods to perform operations.

java
1public enum Planet {
2    MERCURY(3.303e+23, 2.4397e6),
3    VENUS(4.869e+24, 6.0518e6),
4    EARTH(5.976e+24, 6.37814e6);
5
6    private final double mass;   // in kilograms
7    private final double radius; // in meters
8
9    Planet(double mass, double radius) {
10        this.mass = mass;
11        this.radius = radius;
12    }
13
14    public double getMass() { return mass; }
15    public double getRadius() { return radius; }
16
17    // Gravitational constant
18    public static final double G = 6.67300E-11;
19
20    public double surfaceGravity() {
21        return G * mass / (radius * radius);
22    }
23}

In this example, the Planet enum associates each constant with a mass and radius, and includes methods to calculate surface gravity using these values.

Usage and Benefits

Type Safety

Enums provide compile-time type safety which regular constants lack. By enforcing that only defined constants are used, enums help in reducing bugs.

Simplified Syntax

The syntax for enums is much simpler than defining multiple constants individually. You can group related constants, which enhances code readability and maintenance.

Built-in Methods

Many utility methods provided by enums simplify operations such as iteration, conversion of values to strings, and obtaining the ordinal numbers of constants.

Functional Interfaces

Enums can be used alongside Java's functional programming features. For instance, a switch statement or a lambda expression may apply specific logic based on the enum value.

Example in a Switch Statement

java
1Day today = Day.WEDNESDAY;
2
3switch (today) {
4    case MONDAY:
5        System.out.println("Start of work week");
6        break;
7    case FRIDAY:
8        System.out.println("TGIF");
9        break;
10    case SATURDAY, SUNDAY:
11        System.out.println("It's a weekend!");
12        break;
13    default:
14        System.out.println("Midweek day");
15        break;
16}

Enum Table Summary

Below is a table summarizing the key points of Java Enums.

FeatureDescription
Syntaxenum keyword for defining enums.
InheritanceImplicitly extends java.lang.Enum. Cannot be subclassed.
Named ConstantsPredefined set of constants. Example: SUNDAY, MONDAY.
Methodsname(), ordinal(), values().
Fields and ConstructorsCan have fields and constructors to store additional information for enums.
Usage in SwitchEnums can be directly used in switch-case structures.
PerformanceEnums are efficient and fast.
Type SafetyProvides compile-time type safety.
Additional MethodsCan define custom methods similar to class methods.
Combination with LambdasCan be used with functional programming concepts for operations and logic.

Conclusion

Java Enums offer a structured way to define and use constant values, enhancing both the readability and reliability of the code. Through their ease of use, built-in methods, and support for additional functionality, enums represent an important feature of the Java language. By leveraging their power, developers can create more maintainable and error-resistant applications.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.