JavaRush /Java Blog /Random EN /15 Developer Interview Questions Regarding Enum in Java (...
Treefeed
Level 21

15 Developer Interview Questions Regarding Enum in Java (with Answers!)

Published in the Random EN group
Enumeration ( Enum ) was introduced in Java 5 and since then it has become quite popular among Java developers. It is widely used in various Java applications. Because 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 the article 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 became clear from several readers asking, for example, about the ability of Enum to implement an interface in Java or Why we can't instantiate Enums outside of Enum , noting that they were asked about this in an interview. This inspired us to compile a list of frequently asked questions in Java Enum that not only help you succeed in interviews, but also open up new avenues for learning. As stated before, often interview questions force you to take the topic more seriously, which is not a bad thing, and given the power and usefulness of Enum, it's time you became an enum master. Below is a list of questions based on various functionality and properties of Enum. You can use it as preparatory material for an interview or just a guide to enumeration. If you are new to Java, you will learn a lot of new and useful things about Enum. 1) Can Enum 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 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 Enum inherit (extends) class? No, he can not! Unexpected, since it was previously said that the Enum type is similar to a class or interface in Java. Well, this is the main reason why this question is asked right after the previous one. Since Enum already inherits from the abstract class java.lang.Enum , it is clear that another class will not be able to inherit 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 this possible without compilation error? This is one of those tricky questions that interviewers love. Since an Enum is seen as a collection of a certain number of objects, like days of the week or 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 toString() method for Enum? What happens if we don't redefine? Of course you can override Enum's toString() method , as you can override 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 base of the Enum class will does this for you, and will return the 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 is specified when the compiler allocates code to create an enum in response to creating an instance in the Enum class itself, as well as creating an ordinal in the constructor from the java.lang.Enum class : protected Enum(String name, int ordinal) { this.name = name; this.ordinal = ordinal; } This is the only constructor for creating enum , which is called by the compiler in response to the declaration of Enum in the program. 5) Can we instantiate an Enum outside of an Enum? Why not? You can't instantiate an Enum outside the bounds of an Enum because Enum doesn't have a publicconstructor, and the compiler will not allow you to introduce any such constructor. Because the compiler generates most code in response to the Enum type declaration, it does not allow public constructors within Enums, forcing Enum instances to be declared internally. 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 issue that is covered in detail here . 8) What does the ordinal() method do in Enum? The ordinal() method returns the order in which 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 things: that is, indicating that TUESDAY (Tuesday) comes after MONDAY (Monday), and before WEDNESDAY (Wednesday). Similarly, you can use an enumeration to represent months of the year, where February comes after January but comes before March. All custom enumerations inherit this method from the abstract class java.lang.Enum , and they are set by the compiler by calling the protected constructor on java.lang.Enum , which takes a name and an ordinal. 9) Is it possible to use Enum with TreeSet or TreeMap in Java? This is a really interesting Enum question, and one that people like to ask to test their 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 a key requirement for use in ordered collections like TreeSet and TreeMap . Since Enum inherits the Comparable interface by default , it can be used with TreeSet and TreeMap . 10) What is the difference between ordinal() and compareTo() in Enum? This follows directly from the previous question: in fact, compareTo() simulates the order provided by the method ordinal() , 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 a switch case? Yes, you can. Moreover, this is one of the main benefits of using Enum. Since Enum instances compile to a temporary constant, you can safely inject them inside case and switch . Here's an example of 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 well, especially if the 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 through an entire Enum instance? If you've opened java.lang.Enum , you know that the values() method returns an array of all Enum constants. Since every enum inherits java.lang.Enum , they have a values() method . Using it, you can iterate through all the constants of an enumeration of a certain type. Look at examples of this going through with a foreach loop 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 covered in the Effective Java book, it's a popular choice. At first glance, the Enum singleton is promising and quite convenient, such as it controls instantiation, is securely serializable, and above all, it is easy to create a thread-safe singleton using Enum. You no longer need to worry about double checking the volatility of variables. Read more about the pros and cons of using this approach here . 14) What is the benefit of using Enum instead of int enumeration and String enumeration patterns? If you've been programming for more than 5 years and are still in JDK 1.3 or 1.4, you'll be familiar with the String and int enumeration 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 independence of the Enum type, since the String variable responsible for the day of the week can take on any arbitrary value. Likewise, an enumerable int can take on any value, and the compiler will happily swallow it. And using Enum , you get the type safety that the compiler checks for you. There are some interesting thoughts on this topic in Effective Java, which is recommended reading for all Java developers. 15) How to convert String to Enum? This is a daily question that comes up due to the popularity of using 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 String arguments and return it as an Enum . You may also wish to ignore case. Here are some examples of turning strings into enumerations. This brings us to the end of our list of 15 questions ( and answers ) about Enum. But remember: reading is not enough to learn, 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-world experience, and with this experience you will learn more than from examples, since you will encounter more problems that you can handle in more complex and detailed ways. requirements. These questions about Enum are worth paying attention to to test your knowledge, especially if you are in a hurry for an interview and there is simply no time for a detailed immersion in the Enum universe.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION