-
Hajipur, Bihar, 844101
In Java, an enum (short for enumeration) is a special data type that represents a group of named constants. It is used when you have a fixed set of related values that should not change throughout the program — such as days of the week, directions, colors, or months.
Enums make your code more readable and type-safe. Instead of using numbers or strings for constants, enums define meaningful names that belong to a single, organized type.
For example, if you use integers to represent weekdays (1 for Monday, 2 for Tuesday, etc.), it’s easy to make mistakes. Enums prevent that by restricting values to only the defined constants.
Enums simplify programming when you need a fixed set of constant values. Some main benefits are:
Improves readability: The constants have clear names.
Ensures type safety: Only defined constants can be used.
Avoids errors: You cannot assign values outside the enum list.
Supports methods and constructors: Enums can include custom logic.
The syntax for defining an enum is straightforward:
enum EnumName {
CONSTANT1, CONSTANT2, CONSTANT3;
}
Each constant is automatically public, static, and final. You can access them directly using the enum name.
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
public class Main {
public static void main(String[] args) {
Day today = Day.FRIDAY;
System.out.println("Today is " + today);
}
}
Output:
Today is FRIDAY
Here, the variable today can only take one of the predefined constants from the Day enum.
Enums work perfectly with switch statements, making decision-making more readable.
Example:
enum Direction {
NORTH, SOUTH, EAST, WEST
}
public class Main {
public static void main(String[] args) {
Direction dir = Direction.EAST;
switch (dir) {
case NORTH:
System.out.println("Going North");
break;
case SOUTH:
System.out.println("Going South");
break;
case EAST:
System.out.println("Going East");
break;
case WEST:
System.out.println("Going West");
break;
}
}
}
Output:
Going East
Unlike simple constants, enums in Java can have fields, constructors, and methods. This allows you to attach data and behavior to each constant.
Example:
enum Level {
LOW(1), MEDIUM(2), HIGH(3);
private int value;
Level(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
public class Main {
public static void main(String[] args) {
for (Level l : Level.values()) {
System.out.println(l + " level value: " + l.getValue());
}
}
}
Output:
LOW level value: 1
MEDIUM level value: 2
HIGH level value: 3
Explanation:
Each constant (LOW, MEDIUM, HIGH) calls the enum constructor with a specific value. You can also define methods to return these values.
Java automatically provides two useful methods for enums:
values() – returns an array of all enum constants.
valueOf(String name) – returns the constant with the given name.
Example:
enum Month {
JAN, FEB, MAR
}
public class Main {
public static void main(String[] args) {
for (Month m : Month.values()) {
System.out.println(m);
}
Month month = Month.valueOf("FEB");
System.out.println("Selected month: " + month);
}
}
Output:
JAN
FEB
MAR
Selected month: FEB
You can also define methods in enums to perform operations for each constant.
Example:
enum TrafficLight {
RED {
public String action() { return "STOP"; }
},
GREEN {
public String action() { return "GO"; }
},
YELLOW {
public String action() { return "SLOW DOWN"; }
};
public abstract String action();
}
public class Main {
public static void main(String[] args) {
for (TrafficLight t : TrafficLight.values()) {
System.out.println(t + ": " + t.action());
}
}
}
Output:
RED: STOP
GREEN: GO
YELLOW: SLOW DOWN
Here, each constant provides its own implementation of the abstract method action().
You can also use enums in if-else statements just like other types.
Example:
enum Season {
WINTER, SPRING, SUMMER, AUTUMN
}
public class Main {
public static void main(String[] args) {
Season s = Season.SUMMER;
if (s == Season.WINTER)
System.out.println("It's cold");
else if (s == Season.SUMMER)
System.out.println("It's hot");
else
System.out.println("Pleasant weather");
}
}
| Feature | Enum | Class |
|---|---|---|
| Purpose | Represents fixed set of constants | Represents objects with state and behavior |
| Instantiation | Cannot create new instances | Can create new objects using new keyword |
| Inheritance | Implicitly extends java.lang.Enum | Can extend other classes |
| Modifiers | Constants are static and final | Members can be mutable |
| Usage | Used for constant groups | Used for objects and logic |
Enum constants are public, static, and final by default.
Enum can implement interfaces but cannot extend classes.
Enum constructors are private or package-private.
Enum can contain fields, methods, and constructors just like classes.
The ordinal() method returns the position of the constant (starting from 0).
Enums in Java help organize fixed sets of constants in a type-safe and readable manner. They support constructors, methods, and switch statements, making them more powerful than regular constants. By using enums, you make your code cleaner, safer, and easier to understand, especially when dealing with predefined categories like directions, levels, or months.
Create an enum Weekday with constants for all days of the week. Write a program to print “Weekend” if the day is Saturday or Sunday, otherwise print “Weekday”.
Define an enum Month with all 12 months. Add a method getDays() that returns 31 for months having 31 days, 30 for others, and 28 for February. Print the number of days for each month.
Create an enum Level with constants LOW, MEDIUM, and HIGH. Assign each constant a numeric value using a constructor and display all values in a loop.
Write a program using an enum Direction with constants NORTH, SOUTH, EAST, and WEST. Use a switch statement to print a message based on the direction.
Define an enum TrafficSignal with constants RED, YELLOW, and GREEN. Each constant should have a method action() returning what a driver should do (“STOP”, “WAIT”, “GO”). Display all actions.
Create an enum Planet with constants like EARTH, MARS, and JUPITER. Each constant should have a mass and radius. Add a method to calculate surface gravity for each planet and display the results.
Write an enum Color with constants RED, GREEN, and BLUE. Include a method that returns the hexadecimal color code for each constant.
Create an enum Season with constants WINTER, SPRING, SUMMER, and AUTUMN. Add a description field (like “Cold and dry”) for each season and display it using a method.
Write a program using an enum Operation with constants ADD, SUBTRACT, MULTIPLY, and DIVIDE. Each constant should perform the corresponding arithmetic operation using a method apply(int a, int b).
Define an enum MovieGenre with constants ACTION, COMEDY, DRAMA, and HORROR. Add a field description for each and print all genres with their descriptions in a loop.