The enumeration ( Enum ) was introduced in Java 5 and has since become quite popular among Java developers. It is widely used in various Java applications. Since Enum in Java is much more versatile than in C or C++, it also presents many interesting use cases, a couple of which you saw in 10 Ways to Use Enum in Java . But despite this popularity, many Java programmers are still unaware of the functionality provided by Enum and the intricacies of using Enum in Java code.
This was clear from questions from several readers asking, for example, about
the ability of Enum to implement an interface in Java , or
Why can't we create Enum instances outside of Enum , noting that they were asked about this in an interview. This prompted the collection
of a list of frequently asked questions in Java Enum, which not only help you excel in interviews, but also open up new avenues for learning. As mentioned before, interview questions often make you take the topic more seriously, which isn't a bad thing, and given the power and usefulness of Enum, it's about time you become an enum master. Below is a list of questions based on various features and properties of Enum. You can use it as interview prep or just a guide to transfers. If you are new to Java, you will learn a lot of new and useful things about Enum.
1) Can an Enum inherit (implement) an interface in Java? Yes,
Enum can inherit interfaces . Because the Enum type is similar to
a class and
an interface , it can inherit from an interface. This gives amazing flexibility in using Enum as a custom implementation in some cases.
Here is a good example of using Enum in this capacity.
2) Can an Enum inherit (extends) a class? No, he can not! This is surprising, since we said earlier that an Enum type is similar to a class or interface in Java. Well, this is the main reason why this question is asked immediately after the previous one. Since
Enum already inherits from the abstract class
java.lang.Enum, it is clear that another class cannot be inherited, since Java does not support multiple class inheritance. By inheriting from
java.lang.Enum , all enums have
ordinal() ,
values() , or
valueOf() methods .
3) How to create an Enum without object instances? Is it possible without compilation error? This is one of those
tricky questions interviewers love. Since an Enum is seen as a collection of a certain number of objects, like
the days of the week or
the months of the year, getting
an Enum without anything seems suspicious. But yes, you
can create an Enum without instances, for example by creating a utility class. This is another innovative way to use Enum:
public enum MessageUtil{ ; // required to avoid compiler error, also signifies no instance public static boolean isValid() { throw new UnsupportedOperationException("Not supported yet."); } }
4) Can we override the toString() method on Enum? What will happen if we do not redefine? Of course, you can override Enum's
toString() method, as you can any class that inherits
java.lang.Object and has a
toString() method available, and even if you don't, you won't lose anything, because the abstract basis of the Enum class will do this is for you, and will return name, which is the name of the Enum instance. Here is the code for the
toString() method from the Enum class:
public String toString() { return name; }
name
set when the compiler emits code to create an enum in response to instantiation in the Enum class itself, on a par with the creation of an ordinal in a constructor from the java.lang.Enum class :
protected Enum(String name, int ordinal) { this.name = name; this.ordinal = ordinal; }
This is
the only enum constructor that is called by the compiler in response to an Enum declaration in program.
5) Can we instantiate an Enum outside of an Enum? Why not? You
cannot create Enum instances outside of the scope of Enum , because Enum does not have
a public constructor, and the compiler won't let you introduce any such constructor. Because the compiler generates most code in response to an Enum type declaration, it does not allow
publicconstructors inside Enum, which forces you to declare instances of Enum inside yourself.
6) Can we specify a constructor inside an Enum? This question often follows the previous one. Yes, you can, but remember that this is only possible with
private or
package-private constructors. Constructors with
public and
protected are not allowed in Enum. Here you can see
an example.
7) What's the difference between comparing Enum using == or equals() method? This is a very broad and tricky question, covered in detail
here .
8) What does the ordinal() method in Enum do?
ordinal() method
(ordinal) returns the order in which the Enum instances are designated within the Enum. For example, in
the DayOfWeek Enum, you can specify the days in order:
public enum DayOfWeek{ MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY; }
and if we call
the DayOfWeek.MONDAY.ordinal() method , it will return 0 - which means the first instance. This method is very useful for providing order according to the actual state of affairs: i.e. indicating that
TUESDAY (Tuesday) comes after
MONDAY (Monday), and before
WEDNESDAY (Wednesday). Similarly, you can use an enum to represent the months of the year where February comes after January but precedes March. All custom enums inherit this method from the abstract class
java.lang.Enum, and they are set by the compiler by calling
the protected constructor from
java.lang.Enum , which takes a name and an ordinal.
9) Can Enum be used with TreeSet or TreeMap in Java? This is a really interesting question about Enum and is a popular question to test the depth of knowledge. Until you look at the
java.lang.Enum code , you probably won't know that
Enum inherits the Comparable interface , which is the main requirement for use in ordered collections like
TreeSet and
TreeMap .
Because Enum inherits the Comparable interface by default , it can be used with
TreeSet and
treemap .
10) What's the difference between ordinal() and compareTo() in Enum? This is a direct consequence of the previous question: in fact,
compareTo() mimics the order provided by the
ordinal() method , which is the natural order of Enum. In short, Enum restricts comparisons in the order in which they are declared. Also, it is worth remembering that these constants are comparable only with other constants of the same type - comparing different types of constants can lead to a compiler error.
11) Is it possible to use Enum in switch case? Yes, you can. Moreover, this is one of the main benefits of using Enum. Because Enum instances compile to a temporary constant, you can safely embed them inside
case and switch. Here is an example code with days of the week:
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 complement each other perfectly, especially if Enum contains a small number of stable constants, for example, seven days of the week, 12 months of the year, etc. Look at other examples of using swith case
with Enum .
12) How to iterate over the entire Enum instance? If you've looked at
java.lang.Enum , you know that
the values() method returns an array of all Enum constants. Because each enum inherits
java.lang.Enum , they have a
values() method . Using it, you can iterate over all enum constants of a particular type. Look at
examples of such passing with a loop
foreach and
the values() method .
13) What are the pros and cons of using Enum as a singleton? Enum provides
a quick shortcut for implementing the singleton pattern, and since it's even mentioned in Effective Java, it's a popular choice. At first glance, Enum's singleton is promising and quite handy, such as instantiation control, safe serialization, and above all, it's easy to create a thread-safe singleton using Enum. You no longer need to worry about double checking the volatility of variables. Learn more about the pros and cons of using this approach
here .
14) What is the benefit of using Enum instead of the int enum and String enum patterns? If you've been programming for more than 5 years, and still caught JDK 1.3 or 1.4, you'll be on the fast track with the
String and int enum patterns , which use
a public static final constant prefix to represent a collection of well-known fixed numbers of things, like
Days of the Week . There are many problems here: you do not have Enum type independence, since the
String variable responsible for the day of the week can take on any arbitrary value. Similarly, an enumerable
int can take on any value, and the compiler will happily swallow it. And using
Enum, you get type safety which the compiler checks for you. There are some interesting thoughts on this topic in Effective Java, which is a recommended reading for all Java developers.
15) How to convert String to Enum? This is a daily question due to the popularity of
String and
Enum in Java application development. The best way to convert
an Enum to a String is to define a factory method on the Enum itself that will take the
String arguments and return as
the Enum . You may also wish to ignore case. Here are some
examples of how to turn strings into enums. This is the end of our list of 15 questions (
and answers ) about Enum.
But remember:
reading is not enough for learning, it is only the first step . To benefit from enums, try to find where you can use Enum in your project - this will give you real experience, and with this experience you will learn more than with examples, because you will encounter more problems, dealing with which you will process more complex and detailed requirements. These
questions about Enum are worth checking out to test your knowledge, especially if you're in a rush for an interview and don't have time to delve into the Enum universe in detail.
GO TO FULL VERSION