Enum in Java with Examples
Introduction
An enum
(short for enumeration) in Java is a special data type that represents a fixed set of constants. It is used when a variable should only hold predefined values, making the code more readable and less error-prone.
Defining an Enum
In Java, an enum
is defined using the enum
keyword. Here’s a simple example:
enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}
Here, Day
is an enum type with seven predefined constants.
Using an Enum
public class EnumExample {
public static void main(String[] args) {
Day today = Day.WEDNESDAY;
System.out.println("Today is: " + today);
}
}
Output:
Today is: WEDNESDAY
Enum with Constructors and Methods
Enums can have constructors, fields, and methods.
enum Size {
SMALL(10), MEDIUM(20), LARGE(30);
private int value;
Size(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
public class EnumWithMethods {
public static void main(String[] args) {
Size s = Size.MEDIUM;
System.out.println("Size: " + s + ", Value: " + s.getValue());
}
}
Output:
Size: MEDIUM, Value: 20
Iterating Over an Enum
You can use a for
loop to iterate over all constants of an enum
.
public class EnumIteration {
public static void main(String[] args) {
for (Day d : Day.values()) {
System.out.println(d);
}
}
}
Enum in a Switch Statement
Enums are commonly used in switch
statements:
public class EnumSwitch {
public static void main(String[] args) {
Day today = Day.FRIDAY;
switch (today) {
case MONDAY:
System.out.println("Start of the workweek!");
break;
case FRIDAY:
System.out.println("Weekend is near!");
break;
default:
System.out.println("Regular day.");
}
}
}
Output:
Weekend is near!
Enum Implementing an Interface
Enums can implement interfaces:
interface Info {
void display();
}
enum Color implements Info {
RED, GREEN, BLUE;
public void display() {
System.out.println("Color: " + this.name());
}
}
public class EnumWithInterface {
public static void main(String[] args) {
Color c = Color.RED;
c.display();
}
}
Conclusion
Enums in Java provide a way to define a set of constant values in a type-safe manner. They improve code readability and prevent invalid values from being used. By using methods, constructors, and implementing interfaces, enums become powerful tools for handling fixed sets of constants in Java applications.
Sign up here with your email
ConversionConversion EmoticonEmoticon