In Java, an enum is a special class that represents a fixed set of constants. Setting an enum value means assigning one of its predefined constants to a variable, or when the enum has fields, setting those fields through a constructor or a setter. This guide shows you the standard ways to assign enum constants, how to work with enums that carry extra data, and how to update that data safely.
What You’ll Need
- A Java development environment (JDK 8 or later is fine; any modern version works)
- A text editor or IDE (like IntelliJ IDEA, Eclipse, or VS Code)
- Basic familiarity with Java syntax, classes, and methods
Step-by-Step
1. Define a Simple Enum
Create an enum with a set of constants. For example, a Day enum:
public enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
2. Assign an Enum Constant to a Variable
Use the enum type as a variable type and assign one of the constants using dot notation:
Day today = Day.MONDAY;
This is the most common way to “set” an enum value. The variable today now holds the constant MONDAY.
3. Set an Enum Value Through a Method Parameter
Pass an enum constant to a method that expects that enum type:
public void printDay(Day day) {
System.out.println(day);
}
// Call it:
printDay(Day.FRIDAY);
4. Set an Enum Value from a String (Parsing)
If you receive a string and need to convert it to an enum, use the static valueOf method. This is useful for reading input from files or user interfaces:
String input = "WEDNESDAY";
Day day = Day.valueOf(input);
Make sure the string matches exactly (case-sensitive) or it throws IllegalArgumentException.
5. Create an Enum with Fields and a Constructor
Enums can have fields, a constructor, and methods. This is how you attach data to each constant. For example, a Planet enum with mass and radius:
public enum Planet {
MERCURY(3.303e+23, 2.4397e6),
VENUS(4.869e+24, 6.0518e6),
EARTH(5.976e+24, 6.37814e6);
private final double mass; // in kilograms
private final double radius; // in meters
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
public double mass() { return mass; }
public double radius() { return radius; }
}
To “set” a value, you choose a constant, and its fields are already set by the constructor. For example:
Planet earth = Planet.EARTH;
double earthMass = earth.mass();
6. Setting a Mutable Field in an Enum (Advanced)
Although enums are meant to be immutable, you can add a setter for a field if you really need to change it at runtime. This is not recommended, but it’s possible:
public enum Status {
ACTIVE, INACTIVE;
private String description;
public void setDescription(String desc) {
this.description = desc;
}
public String getDescription() {
return description;
}
}
Then set it:
Status current = Status.ACTIVE;
current.setDescription("Running");
Be aware that this changes the value for all references to that enum constant in the entire JVM, which can lead to unexpected side effects.
7. Using EnumSet or EnumMap for Collections
If you need to set multiple enum values in a collection, use EnumSet:
EnumSet<Day> weekend = EnumSet.of(Day.SATURDAY, Day.SUNDAY);
Or a map from enum to values:
EnumMap<Day, String> activities = new EnumMap<>(Day.class);
activities.put(Day.MONDAY, "Gym");
Common Mistakes
- Using
newwith an enum: Enums cannot be instantiated withnew. You must use the predefined constants. - Case sensitivity with
valueOf:Day.valueOf("monday")fails; it must be"MONDAY". - Assuming enums are mutable: Most enums are immutable by design. Adding setters breaks that and can cause bugs.
- Comparing with
==vsequals: Both work, but==is safe for enums because they are singletons. Still, many preferequalsfor clarity. - Forgetting to handle invalid strings:
valueOfthrows an exception for unknown strings. Use a try-catch or a custom lookup method.
Tips
- Use enums instead of int constants for type safety and readability.
- Keep enum fields
finalunless you have a strong reason to change them. - Provide a static
fromStringmethod to safely parse user input:
public static Day fromString(String value) {
for (Day d : Day.values()) {
if (d.name().equalsIgnoreCase(value)) {
return d;
}
}
return null; // or throw an exception
}
- Use
EnumSetfor efficient sets of enum constants. - Override
toString()to provide a user-friendly display name.
Troubleshooting
Problem: valueOf throws IllegalArgumentException.
Solution: Check the string for exact case and spelling. Use a try-catch or a custom lookup that ignores case.
Problem: You get a compile error like “enum types cannot be instantiated”.
Solution: You used new Day(). Remove new and use Day.MONDAY directly.
Problem: Changing a field in one enum constant affects other parts of the program unexpectedly.
Solution: Avoid mutable fields in enums. If you must change state, consider using a separate map or a different design.
Problem: The enum value is null when you try to use it.
Solution: Ensure you assigned it correctly. If parsing from a string, check for null returns from your custom method.
Frequently Asked Questions
Q: Can I set an enum value to null?
A: Yes, you can assign null to an enum variable, but then you cannot call methods on it without a NullPointerException. It’s usually better to avoid null and use an optional constant like UNKNOWN.
Q: How do I iterate over all enum values?
A: Use the static values() method: for (Day d : Day.values()) { ... }.
Q: Can I add methods to an enum?
A: Yes, enums can have methods like any class. You can define abstract methods and override them per constant.
Q: Is it possible to change an enum constant’s name at runtime?
A: No, the name is final by design. You cannot rename a constant, but you can store a separate display name field.
Q: What’s the difference between name() and toString()?
A: name() returns the exact identifier (e.g., “MONDAY”), while toString() can be overridden to return a friendlier version. By default, they are the same.
Q: Can I set an enum value from a database integer?
A: Yes, you can map an integer to an enum by adding an int field and a lookup method. For example, Day.fromCode(1) could return MONDAY.
Related
- Ctrl Button Shortcuts: The Essential List
- C Battery Diameter: Exact Size in mm and Inches
- Balloon Columns with Numbers? Meaning & Use
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- How to Indent in Google Sheets: Simple WorkaroundsGoogle Sheets does not provide a standard Increase Indent button for cell contents. To create a visible indent,…
- Customer List Format in Excel: Fields, Setup, and TipsA useful customer list in Excel has one row per customer and one column for each kind of…
- Excel Consolidate Command: Combine Data Across SheetsIn Excel for Microsoft 365 on Windows, open Data > Consolidate to combine values from multiple ranges into…
- Guest List Excel Template: What to Include and How to UseA guest list Excel template is a workbook for recording invitees, invitation status, RSVPs, attendance details, and seating…
- Excel Data Validation: What Ignore Blank Really MeansYes. In Excel, the Ignore blank checkbox in Data Validation allows an empty cell to pass the rule;…
- Copy an Entire Excel Spreadsheet to a New FileTo copy an entire Excel spreadsheet into a separate file, open the workbook in Excel for Microsoft 365…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.