Explain enums in Java
๐ก Concept: Enums in Java
Enums (enumerations) are a special data type in Java that enable variables to be a set of predefined constants.
๐ Quick Intro
Java enums are used to define collections of constants with type safety and better readability.
๐ง Analogy
Think of enums as a menu list in a restaurant where you can only choose from the items on the menu.
๐ง Technical Explanation
- Enums are declared using the
enum
keyword. - Each enum constant is a static final instance of the enum type.
- Enums can have fields, constructors, and methods.
- Used to restrict variables to predefined values.
- Improve code clarity and prevent invalid values.
๐ฏ Use Cases
- โ Represent fixed sets like days, months, directions.
- โ Use in switch statements for cleaner code.
- โ Enforce compile-time checking of valid values.
๐ป Example: Enum Definition and Usage
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}
public class TestEnum {
public static void main(String[] args) {
Day today = Day.MONDAY;
switch(today) {
case MONDAY:
System.out.println("Start of the work week");
break;
default:
System.out.println("Other day");
}
}
}

โ Interview Q&A
Q1: What is an enum in Java?
A: A special data type with fixed constants.
Q2: Can enums have methods?
A: Yes, they can have methods and fields.
Q3: How do you define an enum?
A: Using the enum keyword.
Q4: Are enums type-safe?
A: Yes.
Q5: Can enums be used in switch?
A: Yes.
Q6: Can enums implement interfaces?
A: Yes.
Q7: Can enums have constructors?
A: Yes, private constructors.
Q8: Are enum constants mutable?
A: No, they are final.
Q9: Can you get enum values as array?
A: Yes, using values() method.
Q10: Difference between enum and final constants?
A: Enums provide type safety and methods.
๐ MCQs
Q1. What is an enum in Java?
- Fixed set of constants
- Mutable class
- Interface
- Data type
Q2. Can enums have methods?
- No
- Yes
- Sometimes
- Depends
Q3. How do you define an enum?
- Using class keyword
- Using interface
- Using enum keyword
- Using final
Q4. Are enums type-safe?
- No
- Yes
- Sometimes
- Depends
Q5. Can enums be used in switch?
- No
- Yes
- Maybe
- Depends
Q6. Can enums implement interfaces?
- No
- Yes
- Maybe
- Depends
Q7. Can enums have constructors?
- No
- Yes
- Maybe
- Depends
Q8. Are enum constants mutable?
- Yes
- No
- Sometimes
- Depends
Q9. Can you get enum values as array?
- No
- Yes
- Maybe
- Depends
Q10. Difference between enum and final constants?
- Same
- Type safety and methods
- Only constants
- No difference
๐ก Bonus Insight
Enums in Java provide a clean, type-safe way to represent fixed sets of constants with added flexibility.
๐ PDF Download
Need a handy summary for your notes? Download this topic as a PDF!