CodeToConcept
About

java

java Tutorials

Introduction
Java Variables
Java Data Types
Java Type Casting
Java Operators
Java Input/Output
Java Class & Object
java Method
Java Constructor
Java this keyword
Java super keyword
Java Method Overloading and Overriding
Java Interface
Java Abstract Class
Java Memory Management
Design Patterns
JDBC (Database Connectivity)
Java IDEs

java Tutorials

Introduction
Java Variables
Java Data Types
Java Type Casting
Java Operators
Java Input/Output
Java Class & Object
java Method
Java Constructor
Java this keyword
Java super keyword
Java Method Overloading and Overriding
Java Interface
Java Abstract Class
Java Memory Management
Design Patterns
JDBC (Database Connectivity)
Java IDEs

Sample Question

Think it through, then check the tutorial.

CodeToConcept

Quickly learn through simple, structured, and practical coding tutorials. Build your confidence from step zero to real-world experience.

© 2026 CodeToConcept. All rights reserved.

Quick Links

AboutTutorials

Tutorials

JavaHTMLCSS

Support

Privacy PolicyTerms of ServiceContact
GitHubTwitterYouTube

Java Enum

Run each complete program separately. Its required helper classes and imports are included in the same code block. Short syntax fragments explain individual operations.

An enum gives a type a named set of instances, such as the allowed states of an order. Code can use those names instead of loosely related strings or numbers. Enum constants can also carry data and behavior, so an enum is more than a list of labels.

For example, if an application has a fixed set of days:

MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY

an enum is a suitable way to represent them.

Instead of using strings:

String day = "MONDAY";

we can define:

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

Then:

Day day = Day.MONDAY;

Enums provide better type safety and make code easier to understand.

What Is an Enum?

An enum is a special Java type that represents a fixed collection of constants.

Syntax

enum EnumName {
    CONSTANT1,
    CONSTANT2,
    CONSTANT3
}

Example

enum Direction {
    NORTH,
    SOUTH,
    EAST,
    WEST
}

We can use it as:

Direction direction = Direction.NORTH;

Why Use Enum?

Suppose an application allows only three order statuses:

PENDING
SHIPPED
DELIVERED

Using a String:

String status = "SHIPPED";

allows invalid values such as:

String status = "UNKNOWN";

With an enum:

enum OrderStatus {
    PENDING,
    SHIPPED,
    DELIVERED
}

we can write:

OrderStatus status = OrderStatus.SHIPPED;

The variable can only hold one of the defined enum constants.

Simple Enum Example

enum Day {
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY
}
 
public class HelloWorld {
 
    public static void main(String[] args) {
 
        Day day = Day.MONDAY;
 
        System.out.println(day);
    }
}

Output

MONDAY

Enum Constants

The values inside an enum are called enum constants.

For example:

enum Color {
    RED,
    GREEN,
    BLUE
}

Here:

RED
GREEN
BLUE

are enum constants.

They are accessed using the enum type:

Color.RED
Color.GREEN
Color.BLUE

Enum Is Type-Safe

Consider:

enum Size {
    SMALL,
    MEDIUM,
    LARGE
}

Now:

Size size = Size.MEDIUM;

is valid.

But:

Size size = "MEDIUM";

is invalid because "MEDIUM" is a String, not a Size.

This is one of the major advantages of enums.

Enum with if-else

Enums can be used with conditional statements.

enum TrafficLight {
    RED,
    YELLOW,
    GREEN
}
 
public class HelloWorld {
 
    public static void main(String[] args) {
 
        TrafficLight light = TrafficLight.RED;
 
        if (light == TrafficLight.RED) {
            System.out.println("Stop");
        } else if (light == TrafficLight.GREEN) {
            System.out.println("Go");
        } else {
            System.out.println("Wait");
        }
    }
}

Output

Stop

Because enum constants are objects of the enum type, comparing them with == is appropriate.

Enum with switch

Enums work very well with switch.

enum Day {
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY
}
 
public class HelloWorld {
 
    public static void main(String[] args) {
 
        Day day = Day.SATURDAY;
 
        switch (day) {
 
            case SATURDAY:
            case SUNDAY:
                System.out.println("Weekend");
                break;
 
            default:
                System.out.println("Weekday");
        }
    }
}

Output

Weekend

Inside a switch on an enum, we normally write:

case SATURDAY:

rather than:

case Day.SATURDAY:

Enum with switch Expression

Modern Java also supports switch expressions.

Example

enum Day {
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY
}
 
public class HelloWorld {
 
    public static void main(String[] args) {
 
        Day day = Day.SUNDAY;
 
        String type = switch (day) {
 
            case SATURDAY, SUNDAY -> "Weekend";
 
            default -> "Weekday";
        };
 
        System.out.println(type);
    }
}

Output

Weekend

values() Method

Every enum provides a values() method that returns an array containing all enum constants.

Example

enum Color {
    RED,
    GREEN,
    BLUE
}
 
public class HelloWorld {
 
    public static void main(String[] args) {
 
        for (Color color : Color.values()) {
 
            System.out.println(color);
        }
    }
}

Output

RED
GREEN
BLUE

valueOf() Method

The valueOf() method converts a matching string into an enum constant.

Example

enum Color {
    RED,
    GREEN,
    BLUE
}
 
public class HelloWorld {
 
    public static void main(String[] args) {
 
        Color color = Color.valueOf("GREEN");
 
        System.out.println(color);
    }
}

Output

GREEN

The string must exactly match an enum constant.

For example:

Color.valueOf("green");

does not match:

GREEN

and throws:

IllegalArgumentException

name() Method

The name() method returns the exact declared name of an enum constant.

Example

enum Status {
    PENDING,
    APPROVED,
    REJECTED
}
 
public class HelloWorld {
 
    public static void main(String[] args) {
 
        Status status = Status.APPROVED;
 
        System.out.println(status.name());
    }
}

Output

APPROVED

toString() Method

Enum constants inherit behavior from Enum, including a toString() method.

By default:

enum Status {
    PENDING,
    APPROVED
}

then:

System.out.println(Status.PENDING);

prints:

PENDING

However, toString() can be overridden when a different display representation is required.

ordinal() Method

The ordinal() method returns the position of an enum constant.

The first constant has ordinal 0.

Example

enum Level {
    LOW,
    MEDIUM,
    HIGH
}
 
public class HelloWorld {
 
    public static void main(String[] args) {
 
        System.out.println(Level.LOW.ordinal());
        System.out.println(Level.MEDIUM.ordinal());
        System.out.println(Level.HIGH.ordinal());
    }
}

Output

0
1
2

Important

Avoid using ordinal() as a permanent business value.

For example, this is fragile:

int status = OrderStatus.SHIPPED.ordinal();

If the order of enum constants changes later, the numeric value changes too.

If an application needs a stable numeric or external value, define an explicit field instead.

Enum with Fields

An enum can contain fields.

Example

enum Status {
 
    PENDING("Order is pending"),
    SHIPPED("Order has been shipped"),
    DELIVERED("Order has been delivered");
 
    private final String description;
 
    Status(String description) {
        this.description = description;
    }
 
    public String getDescription() {
        return description;
    }
}

Usage:

enum Status {
 
    PENDING("Order is pending"),
    SHIPPED("Order has been shipped"),
    DELIVERED("Order has been delivered");
 
    private final String description;
 
    Status(String description) {
        this.description = description;
    }
 
    public String getDescription() {
        return description;
    }
}
 
public class HelloWorld {
 
    public static void main(String[] args) {
 
        Status status = Status.SHIPPED;
 
        System.out.println(status);
        System.out.println(status.getDescription());
    }
}

Output

SHIPPED
Order has been shipped

Enum Constructor

An enum can have constructors.

Example

enum Size {
 
    SMALL("S"),
    MEDIUM("M"),
    LARGE("L");
 
    private final String code;
 
    Size(String code) {
        this.code = code;
    }
 
    public String getCode() {
        return code;
    }
}

Usage:

System.out.println(Size.MEDIUM.getCode());

Output

M

Important Rule About Enum Constructors

Enum constructors are not called directly.

This is invalid:

new Size("M");

Enum constants are created by Java.

We define them:

SMALL("S"),
MEDIUM("M"),
LARGE("L");

and Java creates the corresponding enum instances.

Enum constructors are also implicitly private.

You do not create enum objects using new.

Enum with Methods

An enum can contain methods just like a class.

Example

enum Calculator {
 
    ADD {
        @Override
        public int calculate(int a, int b) {
            return a + b;
        }
    },
 
    SUBTRACT {
        @Override
        public int calculate(int a, int b) {
            return a - b;
        }
    };
 
    public abstract int calculate(int a, int b);
}

Usage:

enum Calculator {
 
    ADD {
        @Override
        public int calculate(int a, int b) {
            return a + b;
        }
    },
 
    SUBTRACT {
        @Override
        public int calculate(int a, int b) {
            return a - b;
        }
    };
 
    public abstract int calculate(int a, int b);
}
 
public class HelloWorld {
 
    public static void main(String[] args) {
 
        System.out.println(
                Calculator.ADD.calculate(10, 5)
        );
 
        System.out.println(
                Calculator.SUBTRACT.calculate(10, 5)
        );
    }
}

Output

15
5

This demonstrates that enum constants can have specialized behavior.

Enum Implementing an Interface

An enum can implement an interface.

Example

interface Printable {
 
    void print();
}

Enum:

enum Color implements Printable {
 
    RED,
    GREEN,
    BLUE;
 
    @Override
    public void print() {
 
        System.out.println(
                "Color: " + this
        );
    }
}

Usage:

interface Printable {
 
    void print();
}
 
enum Color implements Printable {
 
    RED,
    GREEN,
    BLUE;
 
    @Override
    public void print() {
 
        System.out.println(
                "Color: " + this
        );
    }
}
 
public class HelloWorld {
 
    public static void main(String[] args) {
 
        Color.RED.print();
        Color.BLUE.print();
    }
}

Output

Color: RED
Color: BLUE

An enum can implement one or more interfaces.

Enum Cannot Extend Another Class

An enum cannot explicitly extend another class.

For example, this is not allowed:

enum Color extends SomeClass {
}

However, every enum implicitly extends:

java.lang.Enum

This is why an enum cannot extend another class.

Enum and Enum Class

All Java enum types implicitly extend:

java.lang.Enum

For example:

enum Color {
    RED,
    GREEN,
    BLUE
}

conceptually has an inheritance relationship with:

Enum
  ↑
Color

You do not explicitly write:

enum Color extends Enum<Color>

because Java handles this automatically.

Common Methods from java.lang.Enum

Important methods inherited from Enum include:

name()
ordinal()
toString()
compareTo()
equals()
hashCode()
getDeclaringClass()

The enum type also provides the compiler-generated/static methods:

values()
valueOf(String)

Comparing Enum Constants

Enum constants can be compared using ==.

Example

enum Direction {
    NORTH,
    SOUTH,
    EAST,
    WEST
}
 
public class HelloWorld {
 
    public static void main(String[] args) {
 
        Direction direction = Direction.NORTH;
 
        if (direction == Direction.NORTH) {
 
            System.out.println("Moving North");
        }
    }
}

Output

Moving North

Using == is safe for enum constants because each enum constant is a unique instance of its enum type.

Enum in a Class

Enums can be declared separately or inside another class.

Example

class Employee {
 
    enum Department {
        IT,
        HR,
        FINANCE
    }
}

Usage:

class Employee {
 
    enum Department {
        IT,
        HR,
        FINANCE
    }
}
 
public class HelloWorld {
 
    public static void main(String[] args) {
 
        Employee.Department department =
                Employee.Department.IT;
 
        System.out.println(department);
    }
}

Output

IT

Enum Inside a Method

Enums can also be declared locally inside a method or block.

Example

public class HelloWorld {
 
    public static void main(String[] args) {
 
        enum Status {
            STARTED,
            RUNNING,
            COMPLETED
        }
 
        Status status = Status.RUNNING;
 
        System.out.println(status);
    }
}

Output

RUNNING

This can be useful when the enum is needed only in a small local scope.

Enum with Static Members

Enums can contain static fields and methods.

Example

enum MathOperation {
 
    ADD,
    SUBTRACT,
    MULTIPLY;
 
    public static String getDescription() {
        return "Basic mathematical operations";
    }
}

Usage:

System.out.println(
        MathOperation.getDescription()
);

Output

Basic mathematical operations

Enum with Abstract Methods

Each enum constant can provide its own implementation of an abstract method.

Example

enum Operation {
 
    ADD {
        @Override
        int apply(int a, int b) {
            return a + b;
        }
    },
 
    MULTIPLY {
        @Override
        int apply(int a, int b) {
            return a * b;
        }
    };
 
    abstract int apply(int a, int b);
}

Usage:

enum Operation {
 
    ADD {
        @Override
        int apply(int a, int b) {
            return a + b;
        }
    },
 
    MULTIPLY {
        @Override
        int apply(int a, int b) {
            return a * b;
        }
    };
 
    abstract int apply(int a, int b);
}
 
public class HelloWorld {
 
    public static void main(String[] args) {
 
        System.out.println(
                Operation.ADD.apply(10, 5)
        );
 
        System.out.println(
                Operation.MULTIPLY.apply(10, 5)
        );
    }
}

Output

15
50

This is called a constant-specific class body.

Enum with Constructor, Field, and Method

A practical example:

enum HttpStatus {
 
    OK(200, "Success"),
    NOT_FOUND(404, "Resource not found"),
    INTERNAL_ERROR(500, "Internal server error");
 
    private final int code;
    private final String message;
 
    HttpStatus(int code, String message) {
        this.code = code;
        this.message = message;
    }
 
    public int getCode() {
        return code;
    }
 
    public String getMessage() {
        return message;
    }
}

Usage:

enum HttpStatus {
 
    OK(200, "Success"),
    NOT_FOUND(404, "Resource not found"),
    INTERNAL_ERROR(500, "Internal server error");
 
    private final int code;
    private final String message;
 
    HttpStatus(int code, String message) {
        this.code = code;
        this.message = message;
    }
 
    public int getCode() {
        return code;
    }
 
    public String getMessage() {
        return message;
    }
}
 
public class HelloWorld {
 
    public static void main(String[] args) {
 
        HttpStatus status = HttpStatus.NOT_FOUND;
 
        System.out.println(
                "Code: " + status.getCode()
        );
 
        System.out.println(
                "Message: " + status.getMessage()
        );
    }
}

Output

Code: 404
Message: Resource not found

This pattern is useful when each enum constant needs additional information.

Finding an Enum from a Custom Value

Suppose an enum contains an external code.

enum Status {
 
    PENDING("P"),
    APPROVED("A"),
    REJECTED("R");
 
    private final String code;
 
    Status(String code) {
        this.code = code;
    }
 
    public String getCode() {
        return code;
    }
 
    public static Status fromCode(String code) {
 
        for (Status status : values()) {
 
            if (status.code.equals(code)) {
                return status;
            }
        }
 
        throw new IllegalArgumentException(
                "Unknown status code: " + code
        );
    }
}

Usage:

enum Status {
 
    PENDING("P"),
    APPROVED("A"),
    REJECTED("R");
 
    private final String code;
 
    Status(String code) {
        this.code = code;
    }
 
    public String getCode() {
        return code;
    }
 
    public static Status fromCode(String code) {
 
        for (Status status : values()) {
 
            if (status.code.equals(code)) {
                return status;
            }
        }
 
        throw new IllegalArgumentException(
                "Unknown status code: " + code
        );
    }
}
 
public class HelloWorld {
 
    public static void main(String[] args) {
 
        Status status = Status.fromCode("A");
 
        System.out.println(status);
    }
}

Output

APPROVED

This is generally preferable to relying on ordinal() for external codes.

Enum and String

An enum and a string are different types.

Example

enum Status {
    ACTIVE,
    INACTIVE
}

This is valid:

Status status = Status.ACTIVE;

But this is not:

Status status = "ACTIVE";

To convert a string to an enum:

Status status =
        Status.valueOf("ACTIVE");

To convert an enum to its name:

String value =
        Status.ACTIVE.name();

Case Sensitivity of valueOf()

valueOf() is case-sensitive.

This works:

Status.valueOf("ACTIVE");

This does not:

Status.valueOf("active");

It throws:

IllegalArgumentException

If external input may use different capitalization, normalize it before conversion.

Example

Status.valueOf(input.toUpperCase());

For production code, consider how invalid input should be handled rather than assuming conversion always succeeds.

EnumSet

Java provides a specialized collection called EnumSet for enum values.

Example

import java.util.EnumSet;
 
enum Day {
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY
}
 
public class HelloWorld {
 
    public static void main(String[] args) {
 
        EnumSet<Day> weekend =
                EnumSet.of(
                        Day.SATURDAY,
                        Day.SUNDAY
                );
 
        System.out.println(weekend);
    }
}

Output

[SATURDAY, SUNDAY]

EnumSet is designed specifically for enum types and is often more appropriate than a general-purpose Set when the values are enums.

EnumMap

Java also provides EnumMap, a map whose keys are enum values.

Example

import java.util.EnumMap;
import java.util.Map;
 
enum Day {
    MONDAY,
    TUESDAY,
    WEDNESDAY
}
 
public class HelloWorld {
 
    public static void main(String[] args) {
 
        Map<Day, String> schedule =
                new EnumMap<>(Day.class);
 
        schedule.put(Day.MONDAY, "Java");
        schedule.put(Day.TUESDAY, "Spring");
 
        System.out.println(
                schedule.get(Day.MONDAY)
        );
    }
}

Output

Java

Enum as a Singleton

An enum can also be used to implement a singleton.

Example

enum DatabaseConnection {
 
    INSTANCE;
 
    public void connect() {
 
        System.out.println(
                "Connected to database"
        );
    }
}

Usage:

enum DatabaseConnection {
 
    INSTANCE;
 
    public void connect() {
 
        System.out.println(
                "Connected to database"
        );
    }
}
 
public class HelloWorld {
 
    public static void main(String[] args) {
 
        DatabaseConnection.INSTANCE.connect();
    }
}

Output

Connected to database

An enum singleton is a well-known Java pattern because the enum mechanism provides controlled instance creation and serialization behavior.

Enum and Serialization

Enum constants have special serialization behavior in Java.

When an enum constant is serialized, Java preserves its enum identity rather than serializing it like an ordinary object with arbitrary instance state.

This is another reason enum-based singleton implementations are commonly discussed in Java serialization contexts.

Enum vs Constants

Before enums, developers often represented fixed values using constants:

public static final int RED = 1;
public static final int GREEN = 2;
public static final int BLUE = 3;

This has limitations.

For example, another integer can accidentally be assigned:

int color = 999;

There is no type-level restriction that color must be one of the intended values.

With an enum:

enum Color {
    RED,
    GREEN,
    BLUE
}

we can write:

Color color = Color.RED;

This gives us a dedicated type representing the valid choices.

Enum vs String Constants

Using strings:

String status = "APPROVED";

can lead to:

String status = "APPROVE";

The compiler does not know that "APPROVE" is invalid.

With:

enum Status {
    APPROVED,
    REJECTED
}

the compiler can enforce the enum type.

Enum vs Class

An enum is useful when the set of possible instances is fixed and known.

For example:

enum Direction {
    NORTH,
    SOUTH,
    EAST,
    WEST
}

A normal class is more appropriate when objects need to be created dynamically.

Example

class Employee {
 
    private String name;
 
    Employee(String name) {
        this.name = name;
    }
}

You can create many employee objects:

new Employee("John");
new Employee("David");
new Employee("Robert");

With an enum, the constants are a predefined fixed set.

Important Characteristics of Enum

An enum:

  • Is a special Java type.
  • Represents a fixed set of constants.
  • Is implicitly a subclass of java.lang.Enum.
  • Cannot extend another class.
  • Can implement interfaces.
  • Can contain fields.
  • Can contain constructors.
  • Can contain methods.
  • Can contain static members.
  • Can have constant-specific class bodies.
  • Can be used with switch.
  • Can be used with collections such as EnumSet and EnumMap.

Common Mistakes

Mistake 1: Creating an Enum Object with new

Incorrect:

Color color = new Color();

Enum instances are created by Java.

Correct:

Color color = Color.RED;

Mistake 2: Using the Wrong String with valueOf()

This:

Status.valueOf("active");

does not match:

ACTIVE

because enum names are case-sensitive.

Mistake 3: Relying on ordinal() as a Database ID

Avoid:

int id = Status.ACTIVE.ordinal();

If the enum order changes, the value changes.

Prefer an explicit field:

ACTIVE(1)

when a stable external value is required.

Mistake 4: Comparing Enums as Strings

Avoid:

status.name().equals("ACTIVE");

when the comparison is simply between enum constants.

Prefer:

status == Status.ACTIVE

Mistake 5: Assuming Enum Constants Are Strings

This:

Status.ACTIVE

is an enum constant, not a String.

Use:

Status.ACTIVE.name()

if you specifically need its declared name as a string.

Important Enum Methods

MethodPurpose
values()Returns all enum constants
valueOf()Converts matching string to enum constant
name()Returns declared constant name
ordinal()Returns zero-based position
toString()Returns string representation
compareTo()Compares enum constants
getDeclaringClass()Returns enum's declaring class

Complete Practical Example

Consider an order-processing application.

enum OrderStatus {
 
    CREATED("Order created"),
    PROCESSING("Order is being processed"),
    SHIPPED("Order has been shipped"),
    DELIVERED("Order delivered"),
    CANCELLED("Order cancelled");
 
    private final String message;
 
    OrderStatus(String message) {
        this.message = message;
    }
 
    public String getMessage() {
        return message;
    }
}
 
public class HelloWorld {
 
    public static void main(String[] args) {
 
        OrderStatus status =
                OrderStatus.SHIPPED;
 
        System.out.println(
                "Status: " + status
        );
 
        System.out.println(
                "Message: " + status.getMessage()
        );
 
        switch (status) {
 
            case CREATED:
                System.out.println("Order created");
                break;
 
            case PROCESSING:
                System.out.println("Processing order");
                break;
 
            case SHIPPED:
                System.out.println("Order is on the way");
                break;
 
            case DELIVERED:
                System.out.println("Order delivered");
                break;
 
            case CANCELLED:
                System.out.println("Order cancelled");
                break;
        }
    }
}

Output

Status: SHIPPED
Message: Order has been shipped
Order is on the way

This example demonstrates:

  • Enum constants
  • Enum fields
  • Enum constructor
  • Enum method
  • Enum comparison
  • Switch with enum

Frequently Asked Questions

What is an enum in Java?

An enum is a special type used to represent a fixed set of predefined constants.

Can an enum have a constructor?

Yes. Enum constructors are implicitly private and are used when Java initializes the enum constants.

Can we create an enum object using new?

No.

Use:

Color.RED

instead.

Can an enum have methods?

Yes. An enum can contain instance methods, static methods, and even abstract methods.

Can an enum implement an interface?

Yes.

enum Color implements Printable {
}

Can an enum extend a class?

An enum cannot explicitly extend another class because every enum already extends java.lang.Enum.

Can enum constants have different behavior?

Yes. Enum constants can have constant-specific class bodies and provide different implementations of methods.

What does values() do?

It returns all enum constants as an array.

What does valueOf() do?

It returns the enum constant whose name exactly matches the supplied string.

What is ordinal()?

It returns the zero-based position of an enum constant.

Should ordinal() be used as a database ID?

Generally, no. Use an explicit field when a stable external value is required.

Can enums be used in switch?

Yes. Enums are commonly used with switch statements and switch expressions.

Key Points

  • An enum represents a fixed set of constants.
  • Enum constants are accessed using the enum type.
  • Enums provide type safety compared with arbitrary strings or integer constants.
  • Enums can contain fields, constructors, and methods.
  • Enum constructors are implicitly private.
  • Enum objects cannot be created using new.
  • Every enum implicitly extends java.lang.Enum.
  • An enum cannot extend another class.
  • An enum can implement interfaces.
  • Enum constants can have different implementations.
  • values() returns all constants.
  • valueOf() converts a matching string to an enum constant.
  • name() returns the declared name.
  • ordinal() returns the zero-based position.
  • EnumSet is designed for sets of enum values.
  • EnumMap is designed for maps with enum keys.
  • Enum constants can be used safely with ==.
  • Avoid using ordinal() as a persistent business or database value.

Conclusion

Enums are an important Java feature for representing a fixed and well-defined set of values.

Instead of using loosely typed strings or numeric constants:

"SHIPPED"
"DELIVERED"
"cancelled"

we can define a dedicated type:

enum OrderStatus {
 
    CREATED,
    PROCESSING,
    SHIPPED,
    DELIVERED,
    CANCELLED
}

The basic concept can be summarized as:

Enum
  ↓
Fixed Set of Constants
  ↓
Type Safety
  ↓
Fields + Constructors + Methods
  ↓
Switch / Collections / Business Logic

Once basic enums are understood, the next important concepts are enum constructors, enum methods, constant-specific class bodies, EnumSet, EnumMap, and enum-based design patterns.

See you in next page....🙂

← Java Anonymous ClassWrapper Classes →
← Java Anonymous ClassWrapper Classes →