Enum (Enumeration) in Java is a special data type used to define a fixed set of constants. It provides type safety and makes code more readable when a variable can have only a predefined set of values.
Key Points: • Enum represents a group of named constants. • It is used when all possible values are known at compile time. • Enums improve type safety by preventing invalid values. • An enum can contain variables, methods, and constructors, just like a class. • Common use cases include days of the week, order status, user roles, and application states.
Example: Instead of using String values such as "PENDING", "APPROVED", and "REJECTED", an enum can be used to define these statuses in a safer and more maintainable way.
Code Example:
enum Status {
PENDING,
APPROVED,
REJECTED
}
public class Demo {
public static void main(String[] args) {
Status status = Status.APPROVED;
System.out.println(status);
}
}Interview Tip: A concise interview answer is:
"Enum is a special Java data type used to define a fixed set of constants. It provides type safety, improves code readability, and is commonly used when a variable can have only a predefined set of values such as statuses, roles, or days of the week."