Use an enum in Java when a value should be one of a fixed set of named options, such as an order status, day of the week, or access level. Declare the options inside an enum, then refer to them with the enum type name, such as OrderStatus.PAID. Enums make code clearer and safer than representing those choices with arbitrary strings or numbers.
What You’ll Need
- A Java Development Kit (JDK) and a way to compile and run Java code, such as an IDE or the command line.
- Basic familiarity with Java classes, variables, and methods. Enums have been part of Java since Java 5, so a modern JDK supports everything in this guide.
- A small set of values in mind that should be limited to known choices. If users must add new choices while the program is running, an enum may not be the right fit.
Step-by-Step
-
Identify the fixed choices
First list the values that belong to the concept, and check that the set is controlled by the program rather than continually supplied by users. For example, an order might be pending, paid, shipped, or cancelled. Those are mutually exclusive states, and an order status should not contain an unrecognized value such as
"almost shipped". That makes the concept a good candidate for an enum.Enums can also represent categories such as compass directions or supported file formats. Avoid using one just because a variable currently has a few possible values: if the choices are expected to be created or edited dynamically, store them as data instead.
-
Declare the enum
Write the
enumkeyword, a name beginning with an uppercase letter by Java convention, and the constant names inside braces. Put commas between constants and a semicolon after the final one only when you add fields, constructors, or methods.enum OrderStatus { PENDING, PAID, SHIPPED, CANCELLED }Each constant is an instance of
OrderStatus. Enum constants are commonly written in uppercase with underscores between words, for exampleAWAITING_PAYMENT. A top-level enum can be declared in its own file; if it is public, the file name must match the enum name, such asOrderStatus.java. An enum can also be nested inside a class. -
Use an enum as a variable’s type
Declare a variable using the enum type, then assign one of its constants with the type name and a dot. Do not put the constant in quotation marks: it is a typed value, not a string.
OrderStatus status = OrderStatus.PENDING; status = OrderStatus.PAID;A method can accept or return the enum type as well. For example,
void updateStatus(OrderStatus status)limits callers to validOrderStatusvalues. The compiler will reject a misspelled constant or an unrelated type, which prevents many errors that string-based status values would allow. -
Branch on the value with switch
Use a
switchstatement when each enum value needs a different action. In a switch whose selector is an enum, write the constant name without repeating the enum type:switch (status) { case PENDING: System.out.println("Waiting for payment"); break; case PAID: System.out.println("Payment received"); break; case SHIPPED: System.out.println("On the way"); break; case CANCELLED: System.out.println("Order cancelled"); break; }The
breakstatements prevent execution from falling through into the next case in this traditional switch form. You can also useifstatements, but switch is often easier to scan when there are several distinct cases. Consider what should happen for every constant, especially when the enum may gain another value later. -
Loop through all constants
Every enum provides a generated
values()method that returns its constants in their declaration order. Use it to populate a menu, validate a selection, or perform the same operation for each option.for (OrderStatus option : OrderStatus.values()) { System.out.println(option); }This prints
PENDING,PAID,SHIPPED, andCANCELLED. The returned array is a copy, so changing that array does not change the enum’s actual set of constants. Do not assume the order is meaningful unless your program deliberately defines and maintains that order. -
Convert a string when necessary
If a value arrives as text,
valueOf()can convert an exact enum constant name to its enum value:OrderStatus status = OrderStatus.valueOf("PAID");The spelling and capitalization must match the declared constant. An unknown name causes
IllegalArgumentException; passingnullcausesNullPointerException. For external input, check or handle these cases instead of assuming the text is valid. If input should be case-insensitive or use friendly labels, write a conversion method rather than relying onvalueOf(). -
Add fields and behavior if a constant needs extra data
An enum can have fields, a constructor, and methods. This is useful when each choice has a label or other property. Put a semicolon after the list of constants when the enum body continues with members.
enum OrderStatus { PENDING("Waiting for payment"), PAID("Payment received"), SHIPPED("On the way"), CANCELLED("Order cancelled"); private final String label; OrderStatus(String label) { this.label = label; } public String getLabel() { return label; } }Each constant calls the enum constructor with its label. Enum constructors cannot be public or protected; they are effectively private, so code outside the enum cannot create additional instances. The
finalfield makes each label fixed after construction. Read it withstatus.getLabel(). -
Compile and run a small example
Put the enum and a class that uses it in the same source file while learning, or put the public enum in its matching file. Check that the enum name and every constant are spelled consistently. In an IDE, run the class containing
main. At the command line, compile the source file withjavacand run the class withjava, using the class name rather than the source file name for the run command.A useful check is to assign each constant to a variable, print its label, and exercise each switch branch. Once that works, replace the sample status with the value your program actually needs to process.
Common Mistakes
Using quotes around a constant: "PAID" is a String, while OrderStatus.PAID is an enum value. They are different types and cannot be assigned to one another without conversion.
Forgetting the semicolon before members: An enum containing only constants can end the list with a closing brace. If it also declares fields or methods, terminate the constants with a semicolon, even if there is only one constant.
Expecting valueOf() to normalize text: valueOf("paid") does not match PAID. Normalize input deliberately, and decide how to report invalid values instead of letting an exception surprise the user.
Using ordinal() as a permanent identifier: An enum’s ordinal is its zero-based position in the declaration. Inserting a constant can change the positions, so do not store ordinal numbers in a database, file, or external API as stable IDs.
Forgetting to update logic after adding a constant: A switch that handled the old set may no longer express the intended behavior for a newly added value. Review every place that branches on the enum when its list changes.
Tips
- Use enums for a small, known set of alternatives, and choose clear singular type names such as
OrderStatusorDirection. - Compare enum values with
==, for examplestatus == OrderStatus.PAID. Enum constants are unique instances, so identity comparison is appropriate. If a variable might be null,status == OrderStatus.PAIDis also safe and simply evaluates to false. - Keep display text separate from constant names. A label field lets you show “Payment received” to a person without changing the stable code name
PAID. - Enums can implement interfaces, but they cannot extend another class because every enum already extends
java.lang.Enum. Use this when a set of alternatives needs to share a method contract. - Use
name()only when you specifically need the declared constant name.toString()can be overridden for display, so it is not a safe substitute for a stable identifier unless you control that behavior. - Keep enum constants in a useful order for people reading the code, but do not treat declaration order as a business rule unless you intentionally depend on it.
Troubleshooting
“Cannot find symbol” for the enum or a constant: Check capitalization and spelling first; Java is case-sensitive. Confirm the enum is in the same package or imported from its package. If it is public, check that the source file has the matching name.
“Incompatible types” when assigning a value: Make sure the variable and constant use the same enum type. Two enums with identical constant names are still separate types. If you have text, convert it or map it to an enum instead of assigning the string directly.
valueOf() throws an exception: Inspect the incoming value for spaces, different capitalization, or an unexpected label. If input is untrusted, use a conversion method that validates the text and returns a clear error or fallback. Do not catch the exception and silently choose a status unless that fallback is correct for the application.
A switch does not handle a new value: Find every switch over the enum and add an intentional case. If a default branch is used, make sure it does not hide an important new state by treating it as an unrelated case.
A label or field is unavailable: Check that the field is declared inside the enum, the constructor initializes it, and the getter is accessible where it is called. Also verify the constants pass the required constructor arguments.
Frequently Asked Questions
When should I use an enum instead of a String?
Use an enum when the allowed values are known and limited. It gives the compiler a way to reject invalid choices. Use strings or another data structure when choices must be created dynamically or supplied without changing the program.
Can an enum have a constructor and methods?
Yes. An enum can hold fields and define constructors and methods just like a class. Its constructor is not public or protected, and you cannot use new to create an enum constant.
Can an enum contain only one constant?
Yes. A one-value enum is legal, though a regular class or another design may communicate your intent better depending on the use case.
Can I compare enum values with ==?
Yes. Each declared constant is a unique instance, so == is the normal comparison. Avoid calling status.equals(...) if status might be null, because that call would throw a NullPointerException.
How can I get a list of every enum value?
Call the generated values() method, then loop over the returned array. It contains the declared constants in their declaration order.
Can I add new enum values while the program is running?
No. Enum constants are declared in code and form a fixed set. If administrators or users need to add options without changing and rebuilding the program, store those options in a configuration file or data source instead.
Related
- Customizable Invoice Template in Excel: How to Make One
- Daily Attendance Register Template Excel: Setup and Tips
- Customer Details in Excel: How to Set Up a Useful List
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Microsoft PowerPoint: How to Add and Customize TransitionsTo add a transition in Microsoft PowerPoint for Microsoft 365 on Windows, select a slide in the thumbnail…
- Outlook Email Address Examples and How to Choose OneCommon Outlook email address examples include alex.morgan@outlook.com, amorgan27@outlook.com, and alex.morgan@company.com. The first two illustrate personal Microsoft Outlook.com addresses;…
- Outlook Webmail View: Change Layout and Reading PaneTo change your view in Outlook webmail, open Settings (the gear icon), go to Mail > Layout, and…
- Google Sheets: Count Weekdays Between DatesYes. In Google Sheets, use =NETWORKDAYS(A2,B2) to count Monday-through-Friday workdays between the start date in A2 and the…
- Excel X Y Scatter Plot with Multiple Series ExplainedTo make an Excel X Y scatter plot with multiple series, insert a Scatter chart, then use Chart…
- Excel Time Shortcut: How to Insert the Current TimeIn Excel for Microsoft 365 on Windows, select a cell and press Ctrl+Shift+; (semicolon) to enter the current…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.