how to create enum in java
What is Enum in Java?
An enum is a special "data type" that is used to create our own data type like classes. It represents a group of constants (a variable that does not change).
The enum is short for "enumerations", which means "specifically listed" and the Enum data is also known as Enumerated Data Type.
Defining Java Enum
Instead of C/C++, in Java programming language enum types are more powerful. Here, we can define an enum both inside and outside the class, but not inside a method.
Rules to Define Enum in Java:
- 1. To create an enum in Java, use the enum keyword (instead of class or interface), and separate the constants with a comma
- 2. The enum can be defined within or outside the class because it is similar to a class. The semicolon (;) at the end of the enum constants are optional
- 3. Because enums are constants, the names of an enum type's fields are in uppercase letters
Syntax:
enum Directions { EAST, WEST, NORTH, SOUTH; }
// OR (semicolon is optional)
enum Directions { EAST, WEST, NORTH, SOUTH }
Accessing Java Enum
You can access enum constants with the help of dot operator:
Directions myVar = Directions.NORTH;
Examples of Java Enum
Example 1: Enum Defined Inside Class
class EnumExample {
//Defining the enum inside the class
enum Directions {
EAST, WEST, NORTH, SOUTH
} //semicolon(;) is optional here
public static void main(String args[]) {
Directions myvar = Directions.NORTH;
System.out.println(myvar);
}
}
Output:
NORTH
Example 2: Enum Defined Outside Class
//Defining the enum outside the class
enum Directions {
EAST, WEST, NORTH, SOUTH
}
class EnumExample {
public static void main(String args[]) {
Directions direction = Directions.EAST;
System.out.println("Direction: " + direction);
}
}
Output:
Direction: EAST
Example 3: Using Enum in Switch Statement
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
class EnumSwitchExample {
public static void main(String[] args) {
Day today = Day.WEDNESDAY;
switch(today) {
case MONDAY:
System.out.println("Start of work week");
break;
case FRIDAY:
System.out.println("TGIF!");
break;
case SATURDAY:
case SUNDAY:
System.out.println("Weekend!");
break;
default:
System.out.println("Midweek day");
break;
}
}
}
Output:
Midweek day
Built-in Enum Methods
Java enums have several useful built-in methods:
| Method | Description |
|---|---|
values() |
Returns all enum constants as an array |
valueOf(String) |
Returns enum constant with the specified name |
ordinal() |
Returns the position of enum constant (starts at 0) |
name() |
Returns the name of enum constant |
Example: Using Enum Methods
enum Colors {
RED, GREEN, BLUE, YELLOW
}
class EnumMethodsExample {
public static void main(String[] args) {
// Get all enum values
for (Colors color : Colors.values()) {
System.out.print(color + " ");
}
System.out.println();
// Get ordinal value
System.out.println("GREEN position: " + Colors.GREEN.ordinal());
// Get enum by name
Colors myColor = Colors.valueOf("BLUE");
System.out.println("Color name: " + myColor.name());
}
}
Output:
RED GREEN BLUE YELLOW GREEN position: 1 Color name: BLUE
Enum vs. Traditional Constants
❌ Traditional Constants
public class Directions {
public static final int EAST = 0;
public static final int WEST = 1;
public static final int NORTH = 2;
public static final int SOUTH = 3;
}
- • No type safety
- • Can pass any integer
- • No namespace
- • Hard to debug
✅ Java Enum
public enum Directions {
EAST, WEST, NORTH, SOUTH
}
- • Type safe
- • Only valid values allowed
- • Has its own namespace
- • Built-in methods available
Key Benefits of Using Enums
Type Safety
Compile-time checking ensures only valid enum values are used
Better Code Readability
Enum names are more descriptive than magic numbers or strings
Built-in Methods
Access to values(), valueOf(), ordinal(), and name() methods
Can Add Custom Methods
Enums can have constructors, methods, and fields
Best Practices
✅ Do's
- • Use uppercase letters for enum constants
- • Use enums for fixed sets of constants
- • Use enums in switch statements
- • Prefer enums over magic numbers/strings
❌ Don'ts
- • Don't use enums for large sets of values
- • Don't define enums inside methods
- • Don't use lowercase for enum constants
- • Don't forget to use semicolon with custom methods
Summary
Java enums are powerful and type-safe alternatives to traditional constants. They provide better code organization, compile-time checking, and built-in methods for working with a fixed set of related constants.
Enums can be defined inside or outside classes, used in switch statements, and can even have custom constructors, methods, and fields. Always use uppercase letters for enum constants and prefer enums over magic numbers or strings for better code maintainability.