October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk4 min

Enums in Java Explained: Constants, Methods, and Safe Usage

Java enums define a type-safe set of named constants and can also hold fields, methods, and constructor-initialized data. Learn their built-in lookup methods and safe use of names and ordinals.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A Java enum defines a type with a fixed set of named constants, such as days of the week or order states. Use one when the allowed values are known in advance: the compiler then helps prevent invalid values, and the enum can also hold related data and behavior.

What is an enum in Java?

An enum declaration creates a restricted class whose instances are the named constants declared in it. A variable of that enum type can refer only to one of those constants.

As an Amazon Associate I earn from qualifying purchases.

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

For example, Day day = Day.MONDAY; is a type-safe way to represent a day. It is clearer and safer than passing arbitrary strings such as "Monday", where spelling or capitalization mistakes could create unintended values. Oracle recommends enums for sets of values that are known at compile time, including days, menu choices, and command-line flags (Oracle Java Tutorials: Enum Types; Java Language Specification, Java SE 22).

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How do you use an enum in Java?

Refer to a constant with the enum type name, then use it in assignments, comparisons, or a switch. This example uses arrow-style switch labels, available in modern Java; use the syntax supported by your project’s Java version.

Day day = Day.MONDAY;

switch (day) {
    case MONDAY -> System.out.println("Start of the work week");
    case FRIDAY -> System.out.println("End of the work week");
    default -> System.out.println(day);
}

Inside an enum switch, the case labels name constants of the selected enum type. A default branch handles the remaining constants in this example.

How do values() and valueOf() work?

Java provides enum-specific methods for listing constants and looking one up by name.

  • values() returns the constants in the order they appear in the declaration. Use it to iterate over the complete set.
  • valueOf(String) looks up a constant by its exact declared name. The match is case-sensitive and does not ignore extra whitespace; a name that does not match a constant causes an exception rather than returning a fallback value.
for (Day day : Day.values()) {
    System.out.println(day);
}

Day chosen = Day.valueOf("MONDAY");

If a name comes from user input or another untrusted source, validate it or handle the failed lookup instead of assuming it is valid. The Java API documents these methods on Enum (Java SE 26 Enum API).

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Can an enum have a constructor, fields, and methods?

Yes. An enum can associate data and behavior with each constant. The constructor initializes the constants declared in the enum; application code does not call it directly.

public enum Planet {
    EARTH(5.972e24, 6.371e6),
    MARS(6.417e23, 3.3895e6);

    private final double mass;
    private final double radius;

    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }

    public double mass() { return mass; }
    public double radius() { return radius; }
}

Here, each constant supplies values to the enum constructor, and callers can retrieve them through methods such as Planet.EARTH.mass(). This is useful when the values belong naturally to the fixed choices represented by the enum.

What do name(), toString(), and ordinal() mean?

These methods expose different aspects of an enum constant, so choose according to what the value is for.

  • name() returns the exact identifier used in the declaration, such as MONDAY. It is appropriate when that exact name is needed.
  • toString() returns a string representation and may be overridden to provide a more user-friendly label. Do not rely on it when you specifically need the declared identifier.
  • ordinal() returns the constant’s zero-based position in its declaration. It is positional information, not a durable business identifier: reordering constants changes their ordinals.

If an enum value is persisted or exchanged with another system, define an explicit stable code or name and map it deliberately rather than storing its ordinal. The API documents name() and ordinal() (Java SE 26 Enum API).

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

What can enums extend or implement?

Every enum extends java.lang.Enum, so an enum cannot extend an application-defined class. It can implement interfaces, which lets different enum types meet a shared contract.

The Java SE 22 language specification also describes an advanced distinction: an enum with no constant-specific class bodies is implicitly final; if one or more constants have such a body, the enum is implicitly sealed and permits the generated subclasses for those constants. This detail matters when reasoning about advanced inheritance and exhaustiveness, but it is not needed for ordinary enum declarations (Java Language Specification, Java SE 22).

When should you choose an enum?

An enum is a good fit when the set of valid choices is closed and known at compile time. Consider another representation if values are expected to be added dynamically, or if external identifiers need an explicit mapping rather than Java constant names.

  • Choose an enum for a fixed set of choices that benefit from type checking and can be named in code.
  • Add fields and methods when each choice has data or behavior that belongs with it.
  • Use an explicit code or mapping when values cross a persistence or external API boundary and must remain stable independently of declaration order or Java identifiers.

For enum-keyed collections, Java provides specialized EnumMap and EnumSet types. Enum constants also receive special serialization handling, as documented by the Enum API (Java SE 26 Enum API).

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Which Java version do the examples target?

The Oracle tutorial’s enum page was written for JDK 8 and warns that it may not use features from later releases. The switch example above uses modern arrow syntax, so check the Java language level configured for your project before using it. The Java SE 22 specification and Java SE 26 API links cited here document those respective releases; they do not mean that every reader needs to install those versions.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.