Java Enum Interview Questions and Answers (2024)

Java Enum is a feature that was added to Java in version 5. It became quite popular among Java developers and is commonly used in various Java applications.


Here is the list of Enum questions, we will discuss some of the most asked Enum interview questions, like as : What is an enum in Java? or What is the use of enum in java? or What is the benefit of using enums in Java? or What are the different types of enums?

Java Enum

1). What is an Enum?                                      (Most Imp Question)

Java Enum is a special class type that holds constants and they will not change. 


Like as: Name of weeks (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY) 

         or Weather Season (WINTER, SPRING, SUMMER, FALL)

 

Example

public class Enum_Exam {

public enum Week {

SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THRUSDAY, FRIDAY, SATERDAY

}

public static void main(String[] args) {

for (Week w : Week.values()) {

System.out.println(w);

}}}

   

2). Why Enum we are using, in java ?              (Most Imp Question)

Enum is the set of constants, so it is useful when we required to define a set of constants. Enum is useful when list of outcomes is limited.   


3). What are advantages of using Enum in Java?


·     Enum improves safety in java

·     You can’t create objects directly from an enum

·     Enums can be put inside or outside a class.

·     Enum can be easily used in switch case

·     Enum cannot extend any class

·     Enum can have variables, constructors and methods


4). Can we create object of Enum?                  (Most Imp Question)


No, it is not possible to create the object of Enum.


5). What does ordinal() method do in Enum?


In Enum, Ordinal method returns the order in which Enum instance are declared inside Enum. 


Example: in a DayOfWeek Enum, you can declare days in order they come 


public enum WeekDay{

  MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;

}


Ordinal arranges or assigns numbers to each element in Enum starting from 0. MONDAY will be 0, TUESDAY will be 1 and so on. If we call WeekDay.Thursday.ordinal() it will return 3.


6). Can Enum implement interface in Java?


Yes, Enum can implement interface in Java. Since enum is a type, similar to class and interface, it can implement interface.

This flexibility allows enums to be used in specific ways for different situations.



7). How do you create an enum from a String value?


   Function valueOf(String) is used to convert a string to enum.


        //Converting String to Enum

        Season season = Season.valueOf(“FALL”);

  Function name() is used to find String value of an enum.


        //Converting Enum to String

        System.out.println(season.name());//FALL



Note: Enum is useful when list of outcomes is limited.