Top 15 Java Enum Interview Questions Answers for 3 to 5 Years Experienced

Enum was introduced in Java 5 and since then it's been very popular among Java developers and widely used in different Java applications. Since Enum in Java is much more versatile than Enum in C or C++, it also presents lots of interesting use cases, a couple of them, we have seen in my article 10 ways to use Enum in Java. But, despite being so popular, many Java programmers are still not aware of the functionality provided by Enum and the subtle details of using Enum in Java code. 

I realized this fact when a couple of my readers asked me some of the questions like Can Enum implement an interface in Java or Why we can not create Enum instances outside of Enum, stating that these have been asked to them in their Java Interviews.

This motivates me to put together a list of frequently asked question in Java Enum, which not only helps to do well in Interviews but also open a new path for learning.

As I had said before, a lot of time a question in Interviews makes you take a topic more seriously than otherwise, which is not a bad thing, and given the power and facilities offered by Java Enum, I think it's high time to get a master of it.

By the way, if you are new to the Java world then I highly recommend you to go through a comprehensive Java course like The Complete Java Masterclass by Tim Buchalaka and his team to learn essential Java concepts like Enum and Generics. This is also the most up-to-date and comprehensive course with 80+ hours of content but you can buy in just $10 on Udemys sales. 





Java Enum Interview Questions with Answers for 3 to 5 Years Experienced

Here is my list of questions based on the different features and properties of Java Enum. You can use this list for preparing an Interview or simply as a FAQ of Enum. If you are new to Java then I am sure you will learn a lot about Enum and it’s a useful feature.


Question 1. 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. Can we use Enum in the switch case in Java?
Yes, you can use Enum in the Switch case in Java, in fact, that's one of the main advantages of using Enum. Since Enum instances are compile-time constant, you can safely use them inside switch and case statements. 

Here is an example of using our DayOfWeek enum in switch case :




Enum and Switch cases go well with each other, especially if Enum has a relatively small number of fixed constants like 7 days in a week, 12 months in a year, etc, See here for another example of using the switch case with Enum in Java.



Question 3. How do you create Enum without any instance? Is it possible without compile-time error?
This is one of those tricky Java question, which Interviewer love to ask. Since Enum is viewed as a collection of a well-defined fixed number of instances like Days of Week, Month in a Year, having an Enum without any instance, may seem awkward. 

But yes, you can create Enum without any instance in Java, say for creating a utility class. This is another innovative way of using Enum in Java. 

Here is the code

public enum MessageUtil{
;  // required to avoid compiler error, also signifies no instance

public static boolean isValid() {
        throw new UnsupportedOperationException("Not supported yet.");
}

}

Btw, if you are preparing for a Java interview then I also recommend you to check out Educative's Ace the Java Coding Interview track where you will find a lot of courses to prepare essential Java topics for just $14 monthly ($39 dollars usual price). 

best Java interview preparation course





Question 4. Can we override toString() method for Enum? What happens if we don't?
Of course, you can override toString in Enum, as like any other class it also extends java.lang.Object and has toString() method available, but even if you don't override, you will not going to regret it much, because the abstract base class of enum does that for you and return name, which is the name of the enum instance itself. here is the code of the toString() method from the Enum class :

 public String toString() {
        return name;
 }

name is set, when compiler emits code for creating enum in response to instance declaration in enum class itself, along with setting ordinal, as visible in this constructor of enum from java.lang.Enum class :

protected Enum(String name, int ordinal) {
        this.name = name;
        this.ordinal = ordinal;
}

This is the only constructor of creating enum, which is called by code, generated by the compiler in response to enum type declaration in Java program.


Question 5) Can we create an instance of Enum outside of Enum itself? If Not, Why?
Java Enum Interview Questions with Answers for ProgrammersNo, you can not create enum instances outside of the Enum boundary, because Enum doesn't have any public constructor, and the compiler doesn't allow you to provide any public constructor in Enum. Since the compiler generates a lot of code in response to the enum type declaration, it doesn’t allow public constructors inside Enum, which enforces declaring enum instances inside Enum itself.




Question 6. Can we declare Constructor inside Enum in Java?
This is asked along with the previous question on Java Enum. Yes, you can, but remember you can only declare either private or package-private constructor inside enum. public and protected constructors are not permitted inside the enum. See here for a code example.


Question 7. What is the difference in comparing Enum with the == and equals() method?
I have already discussed this question in my post with a similar title, see here.



Question 8. What does the ordinal() method do in Enum?
The ordinal method returns the order in which Enum instances are declared inside Enum. For example in a DayOfWeek Enum, you can declare days in the order they come e.g.

public enum DayOfWeek{
  MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}

here if we call DayOfWeek.MONDAY.ordinal() it will return 0, which means it's the first instance. This ordering can be very useful to represent actual real-world ordering i.e. declaring TUESDAY after MONDAY ensures that it came after MONDAY and before WEDNESDAY

Similarly, you can use an enum to represent the Month of the year in the order they come e.g. FEBRUARY after JANUARY and before MARCH

All user-defined enum inherit this method from java.lang.Enum abstract class, and it's set by the compiler, when it internally calls the protected constructor of java.lang.Enum, which accepts name and ordinal.




Question 9. Can we use Enum with TreeSet or TreeMap in Java?
This is a really interesting question on Java Enum, I would love to ask this to gauge knowledge of Enum. Until you know about java.lang.Enum and has looked at its code.

It's more likely that you don't know that Enum implements a Comparable interface, which is the main requirement to be used in Sorted Collection like TreeSet and TreeMap. Since Enum by default impalement Comparable interface, they can be safely used inside TreeSet or TreeMap in Java.


Question 10.  What is difference between ordinal() and compareTo() in Enum?
This is a follow-up to the previous question on Java Enum. Actually, compareTo() mimic ordering provided by the ordinal() method, which is the natural order of Enum. 

In short Enum constraints are compared in the order they are declared. Also, worth remembering is that enum constants are only comparable to other enum constants of the same enum type. Comparing the enum constant of one type to another type will result in a compiler error.


Question 11. Can Enum extend a class in Java?
No, Enum can not extend the class in Java. Surprised, because I just said it's a type as a class or interface in Java. Well, this is why this question is a good follow-up question to the previous Enum interview question

Since all Enum by default extends abstract base class java.lang.Enum, obviously they can not extend another class, because Java doesn't support multiple inheritances for classes. Because of extending java.lang.Enum class, all enum gets methods like ordinal()values() or valueOf().


Question 12. How to iterate over all instances of an Enum?
Well, if you have explored java.lang.Enum, you know that there is a values() method that returns an array of all enum constants. Since every enum type implicitly extends java.lang.Enum, they get these values() method. By using, this you can iterate over all enum constants of a certain type. See here for an Enum values Example in Java for iterating over Enum using values() and foreach loop.





Question 13. What are the advantages and disadvantages of using Enum as Singleton?
Enum provides you a quick shortcut to implement the Singleton design pattern, and ever since it's mentioned in Effective Java, it's been a popular choice as well. 

On the face, Enum Singleton looks very promising and handles a lot of stuff for you e.g. controlled instance creation, Serialization safety, and on top of that, it’s extremely easy to create thread-safe Singleton using Enum. You don’t need to worry about double-checked locking and volatile variables anymore. See here to know about the pros and cons of using Enum as Singleton in Java.


Question 14. What is the advantage of using Enum over enum int pattern and enum String pattern?
If you have been coding for more than 5 years, and have coded in JDK 1.3 and 1.4, you must be familiar with Enum String pattern and enum int pattern, where we used public static final constants to represent a collection of a well known fixed number of things like DayOfWeek

There were a lot of problems with that approach like you don't have a dedicated enum type Since it's a String variable, which represents days of the week, it can take any arbitrary value. Similarly, the enum int pattern can take any arbitrary value, the compiler doesn't prevent those. 

By using Enum, you get this type-safety and compiler checking for you. There are a couple of good items on this topic in Effective Java, which is once again, a must-read for any Java developer.



Question 15. How to convert a String to Enum in Java?
This is a day-to-day ask, given the popularity of String and Enum in Java application development. The best way for converting Enum to String is to declare a factory method inside Enum itself, which should take String argument and return an Enum. You can choose to ignore the case as well. See here for a code example of String to Enum conversion in Java.


That's all on this list of Java 5 Enum Interview Questions and Answers. Just remember though, reading is not enough for learning, it's just a first step. In order to get proficient with an enum, try to find out where can you use Enum in your project? 

This will give you REAL experience, and with real experience, you learn a lot more than a sample application, because you tend to face more issues, handle the rather complex and detailed requirements. Nevertheless, these Java 5 Enum questions are still worth revising your knowledge, especially if you are rushing for an Interview, and don't have enough time to explore Enum in detail.



Related Interview Questions from Java67 blog

Thanks for reading this article so far. If you like these Java  Enum interviews questions or have seen them on your telephonic round of interviews, then please share this post with your friends and colleagues on Facebook, Twitter, Email, etc. If you have any questions or feedback, please drop a note.

All the best Guys

5 comments:

  1. Hi Javin, excellent article. Though Javin, i would like to find out when we say, creating an enum class without instances, it can be used as a utility class. Don't you think a normal static class would be better in this way. Why would someone go for a Enum in this regard?

    ReplyDelete
    Replies
    1. I think as far as utility class is concern, static class still cut the bill, but enum comes with some handy features e.g. Serialization safety, thread-safe creation, guaranteed Singleton, Ordering etc. So if you need bit of extra from your utility class, I think Enum can be a useful addition.

      Delete
  2. Good think about enum is that you can use them on if and switch case and it also provides a set of valid values which can be used to validate input. Once I was asked, if you compare Enum in if case, what would be better for comparision, equals() method or == opreator?

    ReplyDelete
  3. The argument provided in question 2 is not looking logical to me. If Enum cannot extend other Enum since it already extends default Enum, the same argument can come as a counter question by the interviewer that in that case, why a class can extend another class even if all classes by default extends Object class?

    What is your take on this argument?

    ReplyDelete
  4. The concept of method overloading and overriding is very important for Java developers. I often see one or two question from these topics in Java Phone interviews, it is also important for OCAJP and OCPJP point of view, especially to solve the code based problems.

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.