May 01, 2016

#Java: Enum Interview Questions & Answers


What is Enum in Java?
  • Enumeration (Enum) in Java was introduced in JDK 1.5.
  • Most of the other programming languages like C, C++, etc also provide support for enumerations.
  • Enum is a keyword, a feature which is used to represent a fixed number of well-known values in Java, For example, number of days in a week.
  • Enum constants are implicitly static and final and you can not change their value once created. In short, enumeration is a list of named constants.
  • Enum in Java provides type-safety and can be used inside switch statements like int variables.

What are the benefits of using Enums in Java?
1. 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.

2. 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.

3. You can specify values of enum constants at the creation time. e.g:

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, e.g:

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.

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

5. 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;           
 }

FYI, from JDK 7 onwards we can also String in Switch case in Java code.

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

7. Java compiler automatically generates a 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

8. Enum can override methods also. e.g overridingthe  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();
 }
}; 

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

10. 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.

Comparing enums
As mentioned in the benefits of using Enums, since constants defined inside Enum in Java are final we can safely compare them using "==", the equality operator. We can also use compareTo() for comparison. 

If we try to compare two enum variables from different enumeration using == or compareTo(), we will get compilation error. Though, it is possible to have equals() compare enums of 2 different type, which will always return false.

If we use compareTo() to compare two enums of same type, the result could be:
  • 0: ordinal value of invoking object is equal to the compared object.
  • negative integar: ordinal value of invoking object is less than the ordinal value of compared object.
  • positive integer : ordinal value of invoking object is greater than the ordinal value of compared object.
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 extend 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 the java.lang.Enum class, all enums get methods like ordinal(), values() or valueOf().

Can we create an instance of Enum outside of Enum itself?
No, you can not create enum instances outside of 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 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?

Each enum brings two instance methods: ordinal and name. The former returns the internal id of the enum, which changes if you reorder, insert, or remove entries. Whereas name (and toString) provide the String representation of the enum’s instance name.

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 the compiler, when it internally calls protected constructor of java.lang.Enum, which accepts name and ordinal.

Can we override the 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 a compile time error?
Having an Enum without any instance may seem awkward, but yes it's 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 the 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 instances of an Enum?
By using the values() method we can iterate Enum, it returns an array of all enum constants. 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 the 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 the 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, that's 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.

Can we use Enum in the switch case in Java?
Since Enum instances are compile-time constants, we can safely use them inside switch and case statements.

Can an enum be declared abstract?
No.

Is Enum Serializable in Java?
Java enums are by default Serializable, there is no need to explicitly add the 'implements Serializable' clause following the enum declaration.

What is the default value for enum's serialVersionUID?
By default the serialVersionUID value for all Enums is 0L.

Can an enum constructor be declared public in Java?
No. EThe constructor for an enum type must be package-private or private access.

Can enum have abstract methods in Java?
Yes.

Can a Java enum be subclassed to add new elements?
No Java enum cannot be extended.

Can an enum have a main method in Java?
Surprisingly yes enum can have a startup main method that JVM executes.   

ALSO CHECKCore Java Interview Questions And Answers

Feel free to leave a comment below. If you enjoy our content and want to support us, please consider donating via  gpay, phonepay or paytm on +91 9920600280. Also, I’d appreciate if you’d buy me a coffee☕ 

https://www.buymeacoffee.com/greekykhs


Keep learning and growing!

-K Himaanshu Shuklaa..

No comments:

Post a Comment