Sub topic 1
Your First Enum: Named Constants Done Right
Programs often need a value that can only be one of a few fixed choices. A day of the week can only be one of seven days. A traffic light shows red, yellow, or green. A Java enum is the tool for this kind of fixed set. An enum (short for "enumeration") is a special type that lists every value it can ever have.
This chapter shows why enums exist, how to declare one, and how to use the methods Java gives every enum automatically.
The Problem Enums Solve
Before enums, Java programmers often used plain numbers as constants. A constant is a named value that never changes. Here is the old style:
public class OldDays {
static final int MONDAY = 0;
static final int TUESDAY = 1;
static final int WEDNESDAY = 2;
static void plan(int day) {
System.out.println("Planning for day " + day);
}
public static void main(String[] args) {
plan(MONDAY); // fine
plan(42); // also compiles, but 42 is not a day!
}
}This code compiles and runs, but it has real problems:
- The method accepts any
int, soplan(42)is allowed even though 42 is not a day. - The output says "day 0", which tells a reader nothing.
- Nothing stops you from mixing up unrelated constants, such as passing a month number where a day was expected.
String constants like "MONDAY" are no better. A typo like "MONDYA" still compiles, and the bug only appears when the program runs.
An enum fixes all three problems. The compiler knows the full list of allowed values and rejects anything else.
Declaring an Enum
You declare an enum with the keyword enum, a name, and a list of constants inside braces:
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }Each name in the list is an enum constant. An enum constant is one of the fixed values the enum allows. By convention, constant names use all capital letters, with underscores between words (for example, DARK_GREEN).
Day is now a real type, just like String or int. You can make variables of type Day, pass Day values to methods, and return them:
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
public class Main {
static void plan(Day day) {
System.out.println("Planning for " + day);
}
public static void main(String[] args) {
Day today = Day.MONDAY;
plan(today); // Planning for MONDAY
plan(Day.FRIDAY); // Planning for FRIDAY
// plan(42); // will not compile: 42 is not a Day
}
}Save this as Main.java, then compile and run it with javac Main.java and java Main. Notice two things. First, you write Day.MONDAY to name a constant: the type name, a dot, then the constant. Second, printing a constant prints its name, so the output is readable without any extra work.
Exactly One Object per Constant
Behind the scenes, each enum constant is an object. Java creates exactly one object for each constant when the enum is first used, and never creates any more. You cannot write new Day(). The compiler forbids it.
Because there is only one MONDAY object in the whole program, you can compare enum values safely with ==. The == operator checks whether two references point to the same object.
Day a = Day.MONDAY;
Day b = Day.valueOf("MONDAY");
System.out.println(a == b); // true
System.out.println(a.equals(b)); // true, but == is the usual choiceBuilt-In Methods Every Enum Gets
Java automatically adds several useful methods to every enum. You do not write them yourself.
| Method | What it does | Example result |
|---|---|---|
| `values()` | Returns an array of all constants, in declaration order | `[MONDAY, TUESDAY, ...]` |
| `name()` | Returns the constant's name exactly as declared | `"FRIDAY"` |
| `ordinal()` | Returns the constant's position, starting at 0 | `4` for `FRIDAY` |
| `valueOf(String)` | Finds the constant with that exact name | `Day.FRIDAY` |
| `toString()` | Returns the name by default; used when printing | `"FRIDAY"` |
| `compareTo(other)` | Compares positions in declaration order | negative, zero, or positive |
values() and valueOf() are static methods. A static method belongs to the type itself, so you call it as Day.values(). The others are called on a single constant, as in Day.FRIDAY.name().
Here is a complete program that uses them:
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
public class Main {
public static void main(String[] args) {
for (Day d : Day.values()) {
System.out.println(d.ordinal() + " " + d.name());
}
Day friday = Day.valueOf("FRIDAY");
System.out.println(friday == Day.FRIDAY); // true
System.out.println(Day.values().length); // 7
System.out.println(Day.MONDAY.compareTo(Day.FRIDAY)); // -4
}
}The output is:
0 MONDAY
1 TUESDAY
2 WEDNESDAY
3 THURSDAY
4 FRIDAY
5 SATURDAY
6 SUNDAY
true
7
-4The loop uses values() to visit every constant in the order you declared them. compareTo returns -4 because MONDAY sits at position 0 and FRIDAY at position 4, and 0 minus 4 is -4.
Turning Text into an Enum with valueOf
Programs often read text from users, files, or web requests, then need to turn it into an enum constant. valueOf does this, but it is strict. The diagram shows what happens.
"Exact match" means the case must match and there can be no extra spaces. Day.valueOf("friday") and Day.valueOf(" FRIDAY") both fail. An exception is Java's way of reporting an error while the program runs. If nothing catches it, the program stops.
When the text comes from outside your program, clean it up first and handle the failure case:
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
public class Main {
static Day parseDay(String text) {
if (text == null) {
return null;
}
try {
return Day.valueOf(text.trim().toUpperCase());
} catch (IllegalArgumentException e) {
return null;
}
}
public static void main(String[] args) {
System.out.println(parseDay("friday")); // FRIDAY
System.out.println(parseDay(" Sunday ")); // SUNDAY
System.out.println(parseDay("Funday")); // null
}
}trim() removes spaces from both ends, and toUpperCase() turns "friday" into "FRIDAY". Bad input now gives null instead of crashing the program. Returning null keeps this example simple. Real code often throws a clearer error message or uses a default value instead.
name() Versus toString()
Right now name() and toString() return the same text. The difference matters later. You are allowed to override toString(), which means replacing it with your own version, for example to print "Friday" instead of "FRIDAY". You cannot override name(). It always returns the exact declared name.
So follow this rule:
- Use
toString()(or just print the constant) for text that people will read. - Use
name()when you need the exact name, such as when saving a value so thatvalueOf()can read it back.
A Warning About ordinal()
ordinal() looks handy, but it depends on the order of the constants in the source code. Suppose you save FRIDAY to a file as the number 4. Later someone adds HOLIDAY at the start of the list. Now 4 means THURSDAY, and your saved data is silently wrong.
ordinal() is fine for short-lived uses inside a running program, such as ordering items for display. Java's own enum collections use it internally, but you should not rely on the number lasting between versions of your code.
Where Enums Can Live
You can declare an enum in its own file, next to a class as shown above, or inside a class. An enum declared inside a class is a nested enum:
public class Calendar {
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
public static void main(String[] args) {
Day d = Day.SATURDAY;
System.out.println("Nested enum value: " + d);
}
}Code outside Calendar refers to it as Calendar.Day. A nested enum is a good choice when the enum only makes sense alongside one class.
Summary
- An enum is a type with a fixed list of named constants.
- The compiler rejects values that are not in the list, which prevents a whole class of bugs.
- Each constant is a single object, so
==is the right way to compare them. - Every enum gets
values(),valueOf(),name(),ordinal(),toString(), andcompareTo()for free. valueOf()needs an exact, case-sensitive match and throws an exception otherwise.- Store names, not ordinals.
Exercise
Declare an enum named Season with the constants WINTER, SPRING, SUMMER, and AUTUMN. Write a main method that prints each season's ordinal and name on its own line, using a loop.
Show answer
enum Season { WINTER, SPRING, SUMMER, AUTUMN } and, inside main: for (Season s : Season.values()) { System.out.println(s.ordinal() + " " + s.name()); } The output is "0 WINTER", "1 SPRING", "2 SUMMER", "3 AUTUMN", each on its own line.
Exercise
What happens when each of these lines runs: Day.valueOf("SUNDAY"), Day.valueOf("Sunday"), and Day.valueOf(null)?
Show answer
Day.valueOf("SUNDAY") returns Day.SUNDAY. Day.valueOf("Sunday") throws IllegalArgumentException because the match is case-sensitive. Day.valueOf(null) throws NullPointerException.
Exercise
A teammate saves each user's favorite day to a database as day.ordinal(). Explain the risk and suggest a safer approach.
Show answer
The ordinal depends on the order of the constants in the source code. If someone adds, removes, or reorders constants, the saved numbers will point to the wrong days without any error. A safer approach is to save day.name() and load it back with Day.valueOf(savedText). Another option is to give each constant its own fixed code stored in a field.