Enums in Java are a special type used to represent a fixed and predefined set of constants. They provide a type-safe way to model values that should never change, such as days of the week, order statuses, payment types, or user roles. By using enums, developers can avoid invalid values, improve code readability, and make applications easier to maintain.
Key Points:
• Enums restrict variables to a predefined set of valid values. • They provide compile-time type safety and reduce the chances of programming errors. • Enums are more readable and maintainable than using String or integer constants. • An enum is a special class and can contain fields, constructors, and methods. • They work efficiently with switch statements and business rules.
Example:
In an e-commerce application, an order can have statuses like PENDING, PROCESSING, SHIPPED, or DELIVERED. Using an enum ensures that only these valid statuses can be assigned to an order.
Code Example:
enum OrderStatus {
PENDING,
PROCESSING,
SHIPPED,
DELIVERED
}
public class EnumExample {
public static void main(String[] args) {
OrderStatus status = OrderStatus.PROCESSING;
switch (status) {
case PROCESSING:
System.out.println("Order is being processed.");
break;
case SHIPPED:
System.out.println("Order has been shipped.");
break;
default:
System.out.println("Order status updated.");
}
}
}Interview Tip:
A concise interview answer is: "Enum is a special Java data type used to define a fixed set of constants. It improves type safety, readability, and maintainability by allowing only predefined values to be used, reducing the risk of invalid data in the application."