As you can see, Java Enums are powerful and flexible. There are so many use cases, and they extend into a lot of different domains. They have abilities that are unique (not just within Java, but amongst all non-JVM languages).
That said, everything that is good about enums comes because we make sacrifices along the way. We dont just get this stuff for free – there is a cost. There always is a cost.
As a software engineer, being well-versed in enums (short for enumerations) is a must for acing any technical interview. Enums provide an efficient way to define and manage constants in code, enhancing readability and maintainability. However, many nuances surround their usage, which interviewers love testing candidates on.
In this comprehensive guide, I’ll walk you through the most common enums interview questions, explain core concepts in-depth, and share coding examples in Java and C# to help you master this topic Whether you’re prepping for your dream job or brushing up on skills, let’s dive in!
What are Enums and How are They Used?
The first question aims to assess your foundational understanding of enums An enum is a distinct data type that contains a set of predefined named constants For instance, an enum ‘Days’ could store constants like ‘Monday’, ‘Tuesday’ etc.
Enums are commonly used when a variable should only take a specific set of values. This provides type-safety, as the compiler won’t allow assigning arbitrary values beyond the defined enum constants.
Enums enhance code quality by self-documenting intent reducing bugs and enabling compiler checks. Overall, they simplify coding by letting you use meaningful names rather than literals like ints.
Declaring Enums in Java and C#
Being able to define enums is crucial. Here’s how an enum ‘Days’ would be declared in Java:
public enum Days { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
And in C#:
public enum Days{ Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}
Notice the different naming conventions – Java uses uppercase while C# typically uses PascalCase.
Why Use Enums Over Constants?
This question tests your understanding of the advantages enums provide over traditional constants.
Firstly, enums are type-safe – they restrict assignments to valid constants only. Constants like public static finals have no such checks.
Enums also group related constants, improving readability. Moreover, built-in methods like values()
and valueOf()
make working with enum constants easier.
Enums have inherent serialization support and can be easily used in switch statements. Overall, they reduce bugs and maintenance costs versus constants.
Best Practices for Using Enums
Being aware of best practices demonstrates your experience with real-world enum usage.
Some key points are:
- Use enums for fixed sets of constants
- Use ‘name()’ instead of ‘toString()’
- Prefer switch-case for enums over if-else
- Utilize EnumSet/EnumMap when needed
- Don’t extend enums, implement interfaces instead
- Compare enums using ‘==’, not ‘equals()’
- Capitalize enum constants consistently
Following these will ensure robust enum-driven code.
Calling Enums in Switch Statements
Switch statements are a popular enum use case. Here is how to call an enum constant in a switch expression:
enum Day { MONDAY, TUESDAY //...}Day day = Day.MONDAY;switch(day) { case MONDAY: //code break;}
The key points are:
- Declare the enum outside the switch
- Define a variable of the enum type
- Use that variable in switch expression
- Add case statements for enum constants
This allows clean conditional logic based on enum values.
Implementing Singleton Pattern with Enums
Candidates may be asked to demonstrate using enums creatively, like implementing the Singleton pattern:
public enum Singleton { INSTANCE; public void someMethod() { //... }}
The points to note are:
- Declare an enum with just one constant
- Add required methods to the enum
- Access the instance via
Singleton.INSTANCE
Enums prevent multiple instantiation, making them ideal for the Singleton pattern.
Using EnumSet and EnumMap
EnumSet and EnumMap are specialized collection classes for use with enums.
An EnumSet represents a set of enum values, allowing set operations like add, remove, contains etc.
An EnumMap is a key-value structure with enum keys. It maintains key order.
Knowing when to use these demonstrates your practical knowledge.
Iterating Enums in Java and C#
A common task is iterating over enum values, for which the approaches differ in Java and C#:
Java
for(Days day : Days.values()) { System.out.println(day); }
We use the values()
method which returns an array of the enum constants.
C#
foreach (Days day in Enum.GetValues(typeof(Days))) { Console.WriteLine(day);}
C# requires casting to an array and using GetValues()
.
Implementing Methods in Enums
While enums primarily define constants, you can also add methods:
public enum Day { MONDAY { public void print() { System.out.println("Monday!"); } }}
Here print()
is implemented by overriding the method specifically for MONDAY
.
This demonstrates enums can have polymorphic behavior.
Comparing Enums to Static Constants
This questions tests if you can identify appropriate use cases for enums over constants.
For a fixed set of values like days of the week, enums are preferable since they restrict assignments. Constants like public static final int MONDAY = 0;
have no checks.
Hence, enums provide type-safety making them ideal for a tightly defined set of constants.
Serializing and Deserializing Enums
Knowing how enums serialize and deserialize is imperative.
For serialization, use EnumConstant.name()
– this returns the constant name as a string.
For deserialization, use EnumClass.valueOf(className, constantName)
to get the appropriate enum constant.
Using the built-in methods avoids errors that can occur with custom serialization.
Differences Between Java and C# Enums
This question checks your language depth. Key differences include:
- Java enums can have fields/methods, C# enums are restricted
- Java enums support interfaces, C# doesn’t
- Java allows explicit enum constructors, C# uses initializers
- Java enums are more flexible overall
Knowing language specifics demonstrates well-rounded expertise.
Implementing State Machines
Enums are commonly used in state machines:
public enum State { OFF, ON, STANDBY}
Each constant denotes a state. We can write transition logic between states using enums.
This structure keeps states well-defined and contained.
Enum Constructors
Enum constructors allow initializing instance fields:
public enum Day { MONDAY(1), TUESDAY(2); private int value; Day(int value) { this.value = value; }}
The constructor is called separately for each constant. This demonstrates enums are full-fledged classes in Java.
Handling Enums in Databases
For database persistence, enums can be stored as:
- Integers – simple but rigid
- Strings – more flexible
- Separate table – allows updating independently
The choice depends on factors like flexibility and performance.
ORMs like Hibernate allow mapping enums easily.
Testing Enums
Enum unit testing entails:
- Instantiate the enum
- Initialize with a known value
- Assert against expected value
For example:
@Testvoid testEnum() { Day day = Day.MONDAY; assertEquals(Day.MONDAY, day);}
This verifies the enum works as intended.
Enums in REST APIs
For REST APIs, enums are useful for:
- Path and query parameters – improves type safety
- Response models – communicates fixed options to clients
- Web security – represent roles or permissions
Overall, enums enhance robustness in web apps.
Type Safety
This questions tests your comprehension of enum type safety benefits:
- Compiler checks for invalid assignments
- Meaningful names improve readability
- Errors caught at compile-time, not runtime
- Refactoring/renaming simpler
Proper usage of enums eliminates entire classes of errors.
Additional Enum Fields
Enums can be augmented with fields as:
public enum Color { RED("FF0000"), BLUE("0000FF"); private String code; Color(String code) { this.code = code; }}
Any required fields can be added this way.
Real World Examples
Being able to relate enums to real-world coding demonstrates practical knowledge.
Examples of applying enums include
What else can Java Enums do?
Plus a lot more! In the section on Bounded and Indexed Domain, I talked about how Enums let you tell the compiler EXACTLY how many instances of that type will be present at runtime. I also said that knowing the number of instances at compile-time gives you some POWERFUL guarantees. Here are some of those benefits now.
- Singletons (and Multi-tons): Enums are not only the recommended way to make singletons in Java, they are also the best way to do it (so far). If you only need one instance of an object, you should use an enum instead of making your own singleton.
- Helper Methods Enums come pre-baked with some helpful methods. For example, consider the enum java. time. It shows the days of the week, like Monday, Tuesday, etc., with DayOfWeek. The fact that it is an enum means that these helpful methods are already included. These methods will be built in by default to every other enum you make. valueOf(String name)—If someone sends you a String and you want to turn it into your Enum, all you have to do is call the static method valueOf that comes with your Enum. The String must exactly match your enum values name. But if it does, then its simple, easy deserialization. name() — This method will also take an enum value (like “Monday,” “Tuesday,” etc.) and turn it into a String that exactly matches the name of the enum value. The previous method demonstrated simple, easy deserialization. This method is for simple, easy serialization. values()—You can call this method to get a list of all the values in the right order. In this case, it will give you a list of all the days of the week, starting with MONDAY. You can use this to loop or get an enum value by index. compareTo(E other) — All enums are Comparable by default. It’s easy to tell if the enum value you’re holding comes before or after another enum value. ordinal()—This method can be used to get the positional index of an enum value if you only need it. For example, if you want to pick a value at random from the enum. This might not seem very useful, but it can be used in shockingly powerful ways.
- Enum Collections: Enums have versions of Java that are EXTREMELY FAST and better at using memory. util. Set and java. util. Map — respectfully called java. util. EnumSet and java. util. EnumMap. To show how fast is really fast, I did some very simple and unofficial performance tests and found that EnumMap was over three times faster than Java. util. HashMap. And roughly 15% faster than java. util. IdentityHashMap, which is the non-enum equivalent of EnumMap. You should not use the enum variants if you have an enum and need a set or a map whose keys are the enum. When working with enums, you should always use them. Its a free performance boost. Not only that, but both of these enum variants are ORDERED, which means that comparing EnumMap to HashMap and IdentityHashMap is unfair (for EnumMap!) because EnumMap has a lot more features and functions than the hash variants. A “fair” comparison would be comparing EnumMap to java. util. TreeMap, which is even SLOWER than HashMap and IdentityHashMap. I hope you can see how much more powerful these enum variants are than the rest of the Collection library. And dont forget, I said they are also memory-optimized too. You are not only getting the best performance the Collection library has to offer, but you are also getting one of the lowest memory costs in the library. We can use little memory and run programs quickly because we know HOW MANY INSTANCES THERE ARE AT COMPILE TIME. This means that we can use optimization strategies that aren’t possible for any of the other collections. These enum-variants can use a byte[] (or a bit vector, which is very similar) to show inclusion. For example, the enums ordinal() method is used to represent indexes in an array in EnumSet. It then just puts a 0 or a 1 to show whether the matching enum value is in the set (I told you the ordinal() method could be used for shockingly powerful things). They are so unbelievably fast and light because of this byte. A byte is unbelievably fast and light.
Why to use enum
- enums are implicitly final subclasses of java.lang.Enum
- If an enum is a part of a class, it is automatically static.
- No matter what kind of enum it is, you can’t use new with it.
- name and valueOf just use the enum constants’ text, but toString can be changed to give any content, if needed.
- When it comes to enum constants, equals and == mean the same thing and can be used together.
- enum constants are implicitly public static final
- enums cannot extend any class.
- An enum cannot be a superclass.
- Their “natural order” is the order in which they appear, and it also determines the order in which other things work, like compareTo, iteration order of values, EnumSet, and EnumSet. range.
- It’s possible for an enumeration to have constructors, variables, methods, block and instance variables, but not abstract methods.
Enum inherits all the methods of Object class and abstract class Enum. So you can use its methods for reflection, multithreading, serilization, comparable, etc. If you just declare a static constant instead of Enum, you cant. Besides that, the value of Enum can be passed to DAO layer as well.
Heres an example program to demonstrate.
Use enums for TYPE SAFETY, this is a language feature so you will usually get:
- Compiler support (immediately see type issues)
- IDEs may have tool support, such as auto-completion in switch cases, missing cases, force default, ).
- Sometimes, enums also work very well (EnumSet is a typesafe alternative to traditional int-based “bit flags “).
Enums can have methods, constructors, you can even use enums inside enums and combine enums with interfaces.
Enums are like types that can be used instead of a well-defined set of int constants, which Java got from C/C, and sometimes they can be used instead of bit flags.
The book Effective Java 2nd Edition has a whole chapter about them and goes into more details. Also see this Stack Overflow post.
ENum stands for “Enumerated Type”. It is a data type having a fixed set of constants which you define yourself.
I agree with all of the answers you’ve gotten so far, but here’s how I would say it in a few words:
Use enums if you want the compiler to check the validity of the value of an identifier.
If not, you can use strings the way you always have (most likely, you set some “conventions” for your app), and you will have a lot of options. …but you won’t get 100% security against typos on your strings, and you’ll only find them when the program is running.
You can only give a variable one of a few predefined values in Java. This is called an “enumerated list” value. Using enums can help to reduce bugs in your code. Here is an example of enums outside a class:
This restricts coffeesize
to having either: BIG
, HUGE
, or OVERWHELMING
as a variable.
In my experience I have seen Enum usage sometimes cause systems to be very difficult to change. If your Enum holds a lot of domain-specific values that change often and a lot of other classes and parts depend on it, you might want to think about not using an Enum.
For example, a trading system that uses an Enum for markets/exchanges. There are many markets out there, and it’s likely that many subsystems will need to be able to reach these markets. If you want to add a new market or get rid of an old one, you might have to rebuild and release everything.
A better example would be something like a product category type. Lets say your software manages inventory for a department store. There are a lot of product categories, and many reasons why this list of categories could change. People in charge may want to add a new line of products, get rid of old ones, and sometimes rearrange the categories. If users want to add a product category and you have to rebuild and re-deploy all of your systems, you’ve made something that should be easy and quick (adding a category) very hard and slow.
In the end, enums are good if the data they represent doesn’t change much over time and doesn’t depend on many other things. Having said that, if the data changes often and depends on other data, you need something dynamic that isn’t checked at compile time, like a database table.
Enum? Why should it be used? I think its more understood when you will use it. I have the same experience.
Say you have a create, delete, edit and read database operation.
Now if you create an enum as an operation:
Now, you may declare something like:
So you can use it in many ways. It’s helpful to have enums for certain things, like in the above example, where the currentOperation can be used to control the database operation. Perhaps one can say this can be accomplished with variables and integer values too. But I believe Enum is a safer and a programmers way.
One more thing: I think every programmer loves boolean, right? It can only store two values, exact values. When someone uses Enum, they can set how many and what kind of values it will store in the same way that they would with any other type of class. :).
There are many answers here, just want to point two specific ones:
1) Using as constants in Switch-case
statement. Switch case wont allow you to use String objects for case. Enums come in handy. More: http://www.javabeat.net/2009/02/how-to-use-enum-in-switch/
2) Implementing Singleton Design Pattern – Enum again, comes to rescue. Usage, here: What is the best approach for using an Enum as a singleton in Java?.
The realization that Enum has a private constructor that can only be reached through the public enumeration was the “Aha!” moment for me:
This is the most useful case of enumeration that I can think of for making the code easier to read in the future:
In addition to @BradB Answer :
That is so true. Its strange that it is the only answer who mention that. When beginners discover enums, they quickly take that as a magic-trick for valid identifier checking for the compiler. And when the code is intended to be use on distributed systems, they cry. some month later. Maintain backward compatibility with enums that contains non static list of values is a real concern, and pain. This is because an enum’s type changes when you add a value to it, even though its name doesn’t.
“Hey, wait, it might look like the same type. After all, they have the same name and aren’t enums just integers inside?” Because of these reasons, your compiler probably won’t notice when you use one definition of the type when it was expecting the other. But in fact, they are (in most important ways) different types. Most importantly, they have different data domains – values that are acceptable given the type. By adding a value, we’ve effectively changed the type of the enum and therefore break backward compatibility.
Finally, you can use it whenever you want, but please make sure that the data domain you use is a fixed, known, open set.
Enum | C Technical Interview Questions and Answers | Mr. Srinivas
Why is the enum interview question a good question?
This is why the follow-up question to the preceding Enum interview question is a good one. Since every Enum by default extends Java.lang’s abstract base class. Since Java doesn’t permit multiple inheritance for classes, it stands to reason that Enum cannot extend another class.
Can enum implement an interface in Java?
Yes, Enum can implement an interface in Java. Since enum is a type, similar to class and interface, it can implement an interface. This gives a lot of flexibility to use Enum as a specialized implementation in some cases. You can further see here an example of Enum implementing an interface in Java. Question 2.
Why do enum instances need to be declared inside enum?
Enum instances must be declared inside of Enum because the compiler creates a lot of code in response to the enum type declaration and hence forbids the use of public constructors within of Enum. 13) In Java, can we specify a function object () inside an enum? It is a follow-up query to the Java Enum query.
Why do we use enums?
They provide a way to define and group collections of constants under one umbrella, enhancing code readability and reducing errors caused by parameters that may be out of range. In practice, Enums are used when we want the variable to only accept predefined values.