In Java, an enum value is one of the fixed, named constants declared by an enum type, such as READY or SHIPPED. The generated values() method returns all of a type’s constants, while valueOf() looks up one constant by its exact name.
What “enum value” means in Java
An enum, short for enumeration, defines a type whose possible values are known in advance. For example, a package-delivery status might be PENDING, IN_TRANSIT, or DELIVERED. A variable of that enum type can hold one of those declared constants, not an arbitrary status string.
Each constant is an instance of the enum type. This is an important distinction: an enum is not merely a set of text labels or integer codes. Java creates a fixed instance for each declared constant, and the type system prevents unrelated values from being assigned accidentally. The enum’s constants are implicitly public, static, and final, so they can be referenced directly using the enum type name.
People also use “enum value” to mean different things: a particular constant, the name returned by name(), its position returned by ordinal(), or an application-specific field attached to it. These are related but not interchangeable. In most application code, the constant itself is the meaningful value.
Declaring and using an enum
Declare an enum with the enum keyword. The following example creates a type for a simple order workflow:
enum OrderStatus {
PENDING,
IN_TRANSIT,
DELIVERED,
CANCELLED
}
OrderStatus status = OrderStatus.IN_TRANSIT;
Unlike a string such as "in transit", OrderStatus.IN_TRANSIT is checked by the compiler. Assigning an undeclared name or a constant from another enum type produces a compile-time error. That makes enums useful for representing a closed set of alternatives while keeping code readable.
Enum constants are commonly written in uppercase with underscores, following Java naming conventions for constants. An enum can be declared at top level or inside another class. A nested enum is implicitly static, so it does not need an instance of the surrounding class. Enums can implement interfaces, but they cannot extend another class because every enum type already derives from java.lang.Enum.
How Java enum constants work
Although constants look like bare labels in the declaration, each is an object. Java creates one instance of the enum type for each constant, and those instances are available through the declared names. You can compare enum values with ==; because a given constant has one fixed instance, identity comparison is appropriate and clear.
For example, if (status == OrderStatus.DELIVERED) tests whether the variable contains that exact enum constant. Enums also inherit methods from java.lang.Enum, including name(), ordinal(), and toString(). The name is the identifier as declared; the ordinal is its zero-based position. The default toString() result is the name, though an enum may override that method.
Enum constructors are not called directly by application code. They are used to initialize constants, and enum constructors cannot be public or protected. This supports the closed-set design: callers cannot create extra instances with new and invent values that were not declared.
Getting every value with values()
Every enum type has a compiler-provided static values() method. It returns an array containing the constants in the order in which they appear in the declaration. The method is associated with the specific enum type, so call it as OrderStatus.values(), not as a method on an individual status.
for (OrderStatus item : OrderStatus.values()) {
System.out.println(item);
}
This loop prints each status, in declaration order. values() is useful for building menus, validating choices, populating a user interface, and iterating over every option in tests. Its returned array is an array, so code can technically change an element in that particular array; it does not change which constants the enum declares. Avoid treating the array as a permanent, mutable store of enum configuration.
The method is generated for each enum type rather than inherited from java.lang.Enum. That is why OrderStatus.values() works, but a variable declared only as Enum<?> does not provide a generic values() method. Generic code that must enumerate an enum type needs a type token or another explicit way to obtain its constants.
Looking up a constant with valueOf()
Java also provides a compiler-generated static valueOf(String) method for each enum. It returns the constant whose declared name exactly matches the supplied string:
OrderStatus status = OrderStatus.valueOf("IN_TRANSIT");
The match is case-sensitive and uses the identifier, not a customized display label. For example, valueOf("In transit") does not match IN_TRANSIT. If the input is null, the call throws NullPointerException; if it is not the name of a constant, it throws IllegalArgumentException.
When input comes from a file, API, or user, check and normalize it according to the format you accept before calling valueOf(), and handle invalid input deliberately. Calling toUpperCase() can help only if uppercase identifiers are the agreed input format; it does not convert spaces or alternate labels automatically. For a small number of accepted aliases, an explicit parser or lookup map is usually clearer than relying on names as a public data format.
Adding fields and behavior
An enum can carry data and methods, which is often more useful than storing a separate integer or string beside each constant. Give each constant constructor arguments, define fields, and expose methods to read them:
enum Priority {
LOW(10), NORMAL(20), HIGH(30);
private final int weight;
Priority(int weight) {
this.weight = weight;
}
public int weight() {
return weight;
}
}
Here, Priority.HIGH remains the enum value, while weight() returns additional application-defined data. The field is final, so its value is set when the constant is initialized and cannot later be reassigned. This pattern is safer and more descriptive than scattering numeric codes through conditionals.
Enums can also define methods, implement interfaces, and provide different behavior for individual constants using constant-specific class bodies. These features suit a fixed set of strategies or operations. They should not be used to force a changing collection of data into an enum: if administrators or users need to add options at runtime, a database-backed or configuration-driven model is more appropriate.
Why ordinal() is usually not a stored value
ordinal() returns a constant’s position, starting at zero. In the example, PENDING has ordinal 0 and DELIVERED has ordinal 2. That position can be useful in limited internal algorithms, but it is generally a poor substitute for a stable ID.
Inserting a new constant near the beginning changes the ordinals of later constants. Reordering declarations does too. Therefore, avoid persisting an ordinal in a database, sending it as a long-lived protocol value, or assuming it represents business priority. If an external numeric code is needed, define an explicit field such as weight or code and keep that mapping stable by design.
Similarly, name() returns the exact source-level identifier and is often appropriate for internal diagnostics, but it may be a brittle external representation. Renaming a constant can break stored text or integrations that depend on that spelling. For user-facing text, provide a separate label; for durable interchange, define and document a stable representation.
Choosing enums, strings, and collections
Use an enum when a value must be one of a small, known set and the set is controlled by the program. Compared with strings, enums give compile-time checking, make switch statements clearer, and let an IDE find references when a constant is renamed. Compared with bare numbers, names communicate intent without requiring readers to memorize a code table.
Strings are more suitable when values are open-ended, supplied by users, or need to preserve arbitrary external text. An enum is a poor fit if valid choices change without a software release. For a collection of enum constants, Java’s EnumSet offers a specialized set implementation, and EnumMap is a map whose keys are constants of one enum type. These are useful for representing flags or associating data with each option.
For example, a permissions field could be an EnumSet<Permission> when a user may hold several permissions at once. That differs from storing one enum value: a single enum variable represents one choice, while an enum set represents a group of choices. Pick the model that matches the actual number of simultaneous states.
Common mistakes and practical guidance
- Confusing a label with a constant name: A display string such as “In transit” is not automatically the name
IN_TRANSIT. Keep display text separate when spelling, translation, or punctuation matters. - Using ordinals as IDs: Declaration order can change. Give constants explicit stable codes if an external system requires them.
- Parsing without handling errors: Untrusted input can fail
valueOf(). Validate it or catch the documented exceptions at the boundary where data enters the program. - Expecting a variable’s type to offer values():
values()belongs to a concrete enum type. Code that works generically needs an explicit enum class token or constants supplied by the caller. - Using an enum for a changing catalog: Constants are part of the program’s type definition. Use a data model rather than an enum when choices must be added dynamically.
As a rule of thumb, use the constant itself for comparisons and branching, add explicit fields for meaningful metadata, and treat names or codes as external representations only when you have intentionally chosen and documented them.
Frequently Asked Questions
What does values() return in Java?values() returns an array containing every constant of that enum type in declaration order. It is generated by the compiler for each enum.
What is the difference between valueOf() and values()?values() returns all constants as an array. valueOf(String) returns one constant whose declared name exactly matches the string, or throws an exception if there is no match.
Can I compare Java enum values with ==?
Yes. Each declared constant is a fixed instance, so == is appropriate for checking whether two enum references represent the same constant.
Is an enum ordinal a permanent ID?
No. An ordinal is just the constant’s current zero-based declaration position, which may change if constants are reordered or inserted. Use an explicit code when a stable identifier is required.
Can a Java enum have fields and methods?
Yes. An enum can have constructors, fields, and methods, and can implement interfaces. This lets each constant have associated data or behavior while keeping the set of constants fixed.
Related
- How to Encrypt an Excel File With a Password
- Encrypt an Excel File: Steps, Limits, and Safer Sharing
- Encrypt an Excel Spreadsheet: Steps and Security Tips
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Excel Consolidate Multiple Sheets Into One: 4 MethodsYes. In Excel for Microsoft 365 on Windows, you can combine sheets by appending their rows with Power…
- Indent a New Paragraph in an Excel Cell: Step-by-StepTo indent just one paragraph inside an Excel cell, insert a line break and type spaces at the…
- Outlook Email Signature: How to Create and Set It UpTo create an email signature in Outlook, open the signature settings for your version, write and format your…
- Google Sheets: How to Multiply by a PercentageYes. In Google Sheets, multiply a value by a percentage with =A2*B2 when the number is in A2…
- Microsoft Word Styles: How to Apply and Customize ThemTo use styles in Microsoft Word, place the cursor in a paragraph and choose a style from Home…
- Excel Split Screen: How to Jump Between Panes QuicklyTo jump between panes in a split Excel worksheet, click inside the pane you want to use, or…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.