15 Java Enum Interview Questions for Developers with Answers

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, couple of them, we have seen in my article 10ways to use Enum in Java. But, despite being so popular, many Java programmer are still not aware of functionality provided by Enum and subtle details of using Enum in Java code. I realized this fact, when couple of my readers asked me some of the questions e.g. Can Enum implement an interface in Java or Why we can not create Enum instances outside of Enum, stating that these has been asked to them in there 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 new path for learning. As I had said before, lot of time a question in Interviews, makes you to 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 master of it.


Java Enum Interview Questions with Answers

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

Can Enum implement interface in Java?
Yes, Enum can implement interface in Java. Since enum is a type, similar to class and interface, it can implement interface. This gives a lot of flexibility to use Enum as specialized implementation in some cases. See here for an example of Enum implementing an interface in Java.

Can Enum extends class in Java?
No, Enum can not extend class in Java. Surprised, because I just said it's a type like a class or interface in Java. Well, this is why this question is a good follow-up question of previous Enum interview question. Since all Enum by default extend abstract base class java.lang.Enum, obviously they can not extend another class, because Java doesn't support multiple inheritance for classes. Because of extending java.lang.Enum class, all enum gets methods like ordinal(), values() or valueOf().

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 well defined fixed number of instances e.g. Days of Week, Month in a Year, having an Enum without any instance, may seems 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 instancepublic static boolean isValid() {        throw new UnsupportedOperationException("Not supported yet.");}}

Can we override toString() method for Enum? What happens if we don't?
Ofcourse 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 much, because abstract base class of enum does that for you and return name, which is name of the enum instance itself. here is the code of toString() method from Enum class :

 public String toString() {        return name; }

name is set, when compiler emit 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 compiler in response to enum type declaration in Java program.

Can we create instance of Enum outside of Enum itself? If Not, Why?
No, you can not create enum instances outside of Enum boundry, because Enum doesn't have any public constructor, and compiler doesn't allow you to provide any public constructor in Enum. Since compiler generates lot of code in response to enum type declaration, it doesn’t allow public constructors inside Enum, which enforces declaring enum instances inside Enum itself.

Can we declare Constructor inside Enum in Java?
This is asked along with 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 enum. See here for a code example.

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

What does ordinal() method do in Enum?
Ordinal method returns the order in which Enum instance are declared inside Enum. For example in a DayOfWeek Enum, you can declare days in 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 enum to represent Month of 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 compiler, when it internally call protected constructor of java.lang.Enum, which accepts name and ordinal.

Can we use Enum with TreeSet or TreeMap in Java?
This is 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 it's code, it's more likely that you don't know that Enum implements Comparable interface, which is 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.

What is difference between ordinal() and compareTo() in Enum?
This is follow-up of previous question on Java Enum. Actually, compareTo() mimic ordering provided by 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 enum constant of one type to another type will result in compiler error.

Can we use Enum in switch case in Java?
Yes, you can use Enum in Switch case in Java, in fact that's one of the main advantage 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 :

public void developerState(DayOfWeek today){        switch(today){            case MONDAY:                System.out.println("Hmmmmmmmm");                break;            case TUESDAY:                System.out.println("Hmmmm");                break;            case FRIDAY :                System.out.println("Yeahhhhhh");                break;        }     }

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

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

What is advantage and disadvantage of using Enum as Singleton?
Enum provides you a quick shortcut to implement 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 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 variable anymore. See here to know about pros and cons of using Enum as Singleton in Java.

What is advantage of using Enum over enum int pattern and enum String pattern?
If you are coding from 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 collection of well known fixed number of things e.g. DayOfWeek. There was lot of problem with that approach e.g. you don't have a dedicated enum type, Since it's String variable, which represent day of week, it can take any arbitrary value. Similarly enum int pattern can take any arbitrary value, compiler doesn't prevent those. By using Enum, you get this type-safety and compiler checking for you. There are couple of good items on this topic in Effective Java, which is once again, must read for any Java developer.

How to convert an String to Enum in Java?
This is a day to day ask, given popularity of String and Enum in Java application development. 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 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 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 lot more than a sample application, because you tend to face more issues, handle rather complex and detailed requirement. Nevertheless, this Java 5 Enum questions are still worth for revising your knowledge, especially if you are rushing for an Interview, and don't have enough time to explore Enum in detail.

Related Java Interview Tutorials from Java67 blog
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值