May 01, 2016

Enum Interview Questions & Answers

What is Enum in Java?
Enumeration (Enum) in Java was introduced in JDK 1.5. It is a keyword, a feature which is used to represent fixed number of well-known values in Java, For example, Number of days in Week.

Enum constants are implicitly static and final and you can not change their value once created. Enum in Java provides type-safety and can be used inside switch statement like int variables.

Benefits of using Enums in Java
A. prior JDK 1.5 enumerable values can be represented as :

public class CurrencyDenom {
   public static final int PENNY = 1;
   public static final int NICKLE = 5;
}
public class Currency {
   private int currency;
}

It was not type-safe as we can assign any valid int value to currency e.g. 99 though there is no coin to represent that value.

public enum Currency {PENNY, NICKLE, DIME, QUARTER};

However, Enum is type-safe you can not assign anything else other than predefined Enum constants to an Enum variable. It is a compiler error to assign something else, unlike the public static final variables used in Enum int pattern and Enum String pattern.

B. To access the currencyDenom constant we need to prefix class name e.g. CurrencyDenom.PENNY instead of just using PENNY though this can also be achieved by using static import in JDK 1.5. However, Enum has its own namespace.

C. You can specify values of enum constants at the creation time like:
public enum Currency {PENNY(1), NICKLE(5), DIME(10), QUARTER(25)};

But for this to work you need to define a member variable and a constructor because PENNY (1) is actually calling a constructor which accepts int value, like:

public enum Currency {
        PENNY(1), NICKLE(5);
        private int value;
        private Currency(int value) {
                this.value = value;
        }
}; 

"The constructor of enum in java must be private," any other access modifier will result in compilation error. Now to get the value associated with each coin you can define a public getValue() method inside Java enum like any normal Java class. Also, the semicolon in the first line is optional.

D. Enum constants are implicitly static and final and can not be changed once created.

F. Enum in java can be used as an argument on switch statement and with "case:" like int or char primitive type. This feature of java enum makes them very useful for switch operations. Let’s see an example of how to use java enum inside switch statement: 

 Currency usCoin = Currency.DIME;
    switch (usCoin) {
            case PENNY:
                    System.out.println("Penny coin");
                    break;
            case NICKLE:
                    System.out.println("Nickle coin");
                    break;           
 }

* From JDK 7 onwards you can also String in Switch case in Java code.

E. Since constants defined inside Enum in Java are final you can safely compare them using "==", the equality operator

F. Java compiler automatically generates static values() method for every enum in java. Values() method returns array of Enum constants in the same order they have listed in Enum and you can use values() to iterate over values of Enum  in Java as shown in below example:

for(Currency coin: Currency.values()){
   System.out.println("coin: " + coin);
}

And it will print:
coin: PENNY
coin: NICKLE

G. Enum can override methods also. e.g overriding toString() method inside Enum in Java to provide a meaningful description for enums constants.

public enum Currency {     
  @Override
  public String toString() {
       switch (this) {
         case PENNY:
              System.out.println("Penny: " + value);
              break;
         }
  return super.toString();
 }
}; 

H. You can not create an instance of enums by using new operator in Java because the constructor of Enum in Java can only be private and Enums constants can only be created inside Enums itself.

I. Enum in Java can implement the interface and override any method like normal class It’s also worth noting that Enum in java implicitly implements both Serializable and Comparable interface.


Can Enum implement an interface?
Yes. Since enum is a type, similar to class and interface, it can implement interface. This gives a lot of flexibility to use.

Can Enum extends class in Java?
No, Enum can not extend class 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().

Can we create instance of Enum outside of Enum itself?
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.

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. 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 override compareTo method for Enumerations?
NO. compareTo method is declared final for the Enumerations and hence cannot be overriden. This has been intentionally done so that one cannot temper with the sorting order on the Enumeration which is the order in which Enum constants are declared.

How do you create Enum without any instance? Is it possible without compile time error?
Having an Enum without any instance, may seems awkward, but yes its possible to create Enum without any instance in Java (say for creating a utility class). This is another innovative way of using Enum in Java. e.g:

public enum MessageUtil{
;  // required to avoid compiler error, also signifies no instance
public static boolean isValid() {
        throw new UnsupportedOperationException("un supported exception..");
}
}


Can we use Enum with TreeSet or TreeMap in Java?
Enum implements Comparable interface, which is main requirement to be used in Sorted Collection like TreeSet and TreeMap. That's why Enum can be safely used inside TreeSet or TreeMap in Java.

How to iterate over all instance of a Enum?
By using values() method we can iterate Enum, it returns an array of all enum constant. Since every enum type implicitly extends java.lang.Enum, they get this values() method.

How to parse String to Enum in Java?
Enum classes by default provide valueOf (String value) method which takes a String parameter and converts it into an enum.  String must be same as declared Enum otherwise, the code will throw "java.lang.IllegalArgumentException: No enum const class".

'valueOf()' is a static method, which is added on every Enum class during compile time and it's implicitly available to all Enum along with values(), name() and ordinal() methods.

e.g
public class LanguageTest {
    private enum LANG {
        GERMAN_LANG {
            @Override
            public String toString() {
                return "the language is German";

            }
        },
        ENGLISH_LANG {
            @Override
            public String toString() {
                return "the language is English";
            }
        }
    }

    public static void main(String[] args) {
        // Exmaple of Converting String to Enum in Java
        LANG germanLang = LANG.valueOf("GERMAN_LANG");
        System.out.println(germanLang);

        LANG englishLang = LANG.valueOf("ENGLISH_LANG");
        System.out.println(englishLang);
    }
}

Output will be:
the language is German
the language is English


How to convert Enum to String in Java?
There are multiple ways to convert an Enum into String, one way is to return exact same String used to declare Enum from toString() method of Enum, otherwise if you are using toString() method for another purpose then you can use default static name() method to convert an Enum into String. Java by default adds name() method into every Enum and it returns exactly same text which is used to declare enum in Java file.

 public static void main(String[] args) {
        String germanLang = LANG.GERMAN_LANG.name();
        System.out.println(germanLang);

        String englishLang = LANG.ENGLISH_LANG.name();
        System.out.println(englishLang);   
}

Output will be:
GERMAN_LANG
ENGLISH_LANG


Is it possible to define main() method inside enum?
Yes, we can define main() method inside enum.

Can we declare constructors inside enum?
Yes.

Inheritance concept is applicable for enum?
enum is always declared as final, so we can’t extend it, thats why inheritance concept is not applicable for enum.

When and how the constructor of Enum is called?
Let's create a singleton class using Enum like this, JVM will implicitly insert a no argument constructor.
public enum MySingleton{INSTANCE;}

Let's be explicit instead:
public enum MySingleton {
    INSTANCE;
    private MySingleton() {
        System.out.println("Inside constructor of MySingleton");
    }
}


Now when you call 'MySingleton.INSTANCE' for the first time, explicit constructor will be called.

System.out.println(MySingleton.INSTANCE);


this will give output as:
Inside constructor of MySingleton
INSTANCE


Where as output of:
System.out.println(MySingleton.INSTANCE);
System.out.println(MySingleton.INSTANCE);


will be:
Inside constructor of MySingleton
INSTANCE
INSTANCE


enum fields are compile time constants, but they are instances of their enum type. And, they're constructed when the enum type is referenced for the first time.

-K Himaanshu Shuklaa..

No comments:

Post a Comment

RSSChomp Blog Directory