Java - Interview Questions and Answers on Enumeration or Enum

Q1.  What are concepts introduced with Java 5 ?

Ans. Generics , Enums , Autoboxing , Annotations and Static Import.

Q2.  When were Enums introduced in Java ?

Ans. Enums were introduced with java 5.

Q3.  What is an Enum type ?

Ans. An enum type is a special data type that enables for a variable to be a set of predefined constants

Q4.  If I try to add Enum constants to a TreeSet, What sorting order will it use ?

Ans. Tree Set will sort the Values in the order in which Enum constants are declared.

Q5.  Can we override compareTo method for Enumerations ?

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

Q6. What will be the output of following code ?

enum Day {
     MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY,SUNDAY
}

public class BuggyBread1{
   public static void main (String args[]) {
     Set<Day> mySet = new HashSet<Day>();
     mySet.add(Day.SATURDAY);
     mySet.add(Day.WEDNESDAY);
     mySet.add(Day.FRIDAY);
     mySet.add(Day.WEDNESDAY);
     for(Day d: mySet){
      System.out.println(d);
     }
   }
}

Ans. WEDNESDAY, FRIDAY and SATURDAY will be printed but their order cannot be predicted.

Set doesn't allow duplicates and HashSet doesn't maintain any order.

Q7.  What will be the output of following code ?

enum Day {
 MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY,SUNDAY
}

public class BuggyBread1{

    public static void main (String args[]) {
     Set<Day> mySet = new TreeSet<Day>();
     mySet.add(Day.SATURDAY);
     mySet.add(Day.WEDNESDAY);
     mySet.add(Day.FRIDAY);
     mySet.add(Day.WEDNESDAY);
     for(Day d: mySet){
      System.out.println(d);
     }
    }
}

Ans. WEDNESDAY 
FRIDAY
SATURDAY

Only one FRIDAY will be printed as Set doesn't allow duplicates.

Elements will be printed in the order in which constants are declared in the Enum. TreeSet maintains the elements in the ascending order which is identified by the defined compareTo method. compareTo method in Enum has been defined such that the constant declared later are greater than the constants declared prior. 

Q8.  Can we extend an Enum ?


Ans. No. Enums are final by design.