Search Tutorials


Top Java Enum frequently asked interview questions | JavaInUse

Top Java Enum frequently asked interview questions


In this post we will look at Enum Interview questions. Examples are provided with explanation.


Q: Why do we have the concept of enum?
A:
Enum is the lists of constants, so it is useful when required to define a list of constants. Enum is useful when list of outcomes is limited.

Q: Can Enum constants can be declared as static and final?
A:
Yes. Enum constants are public static and final and are accessible directly using enum name.

Q: Can a constuctor be invoked using an Enum?
A:
Yes we can use the constuctor with the name of Enum.
Enum Color
{  RED,GREEN	}
Color()
{	System.out.println("This is constuctor");	}
	


Q: Can we extend an Enum to add elements?
A:
No, we cannot extend Enum further in the Code. It is defined only with keyword Enum and filled with elements but these elements cannot be added further in the program using some alternative method.

Q: Can we create object of Enum?
A:
No, it is not possible to create the object of Enum.

Q: What are advantages of using Enum in Java?
A:
1.) Enum improves safety
2.) Enum can be placed in or out of a class
3.) Enum can be easily used in switch case
4.) Enum cannot extend any class
5.) Object of enum cannot be made
6.) Enum can have variables, constructors and methods


Q: Give an example of using Enum using switch case?
A:
Enum can be passed as an argument in switch case: package com.java1;
public class SwitchEnum {
	enum Color
	{
		RED,GREEN,BLUE
	}
	public static void main(String[] args) {
		
		Color k;
		k = Color.GREEN;
		
		switch(k)
		{
		case RED:
			System.out.println("I am "+k);
			break;
		case GREEN:
			System.out.println("I am "+k);
			break;
		case BLUE:
			System.out.println("I am "+k);
			break;
		
		}	
	}
}


Q: What does ordinal() method do in Enum?
A:
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 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.

Q: Can Enum implement interface in Java?
A:
Yes, Enum can implement interface in Java. Since enum is a type, similar to class and interface, it can implement interface. This gives a lot of flexibility to use Enum as specialized implementation in some cases

See Also

Spring Batch Interview Questions Apache Camel Interview Questions JBoss Fuse Interview Questions Drools Interview Questions Java 8 Interview Questions