What is Enumeration in Java? A Beginners Guide

Related Courses

Next Batch : Invalid Date

Next Batch : Invalid Date

Next Batch : Invalid Date

Next Batch : Invalid Date

Next Batch : Invalid Date

Next Batch : Invalid Date

Enumeration in Java

By Enumeration, we mean a set of named constants that has its data type. If you can sort out the type of the variable while curating a program, you find it simple while defining them. Hence, Enum applies when you know all the values at the compile time. And we are going to discuss the Enumeration in Java through a list of examples. The topics covered in this article are like what is Enumeration in Java, what its definition is, how we can create enumeration using switch case, what are Values () and ValueOf() method, what are the Enumeration and constructor, instance variable, and method. And you can contact us for your Java training. Naresh I Technologies is the number one computer training institute in Hyderabad and among the top five computer training institutes in India. Contact us anytime for your Java training. 

 

What is Enumeration in Java?

Enumeration happens to be a named constant. When we talk of it in Java, it is a class type and comes with Constructors. We create it through the Enum keyword. And by default, each of the enumeration constant happens to be static, public, and final. The enumeration is a class type and comes with the constructors, you don’t need to instantiate the Enum through the Enum variable. And we define the Enum variable in the same manner like we define the primitive variable. 

Now let’s have the details of the Enumeration, and know the syntax and the declaration of Enum.

Defining Enumeration in Java

We can declare the Enum outside the class or within the class as well. However, we cannot do its declaration within the method. Below is an example of the declaration.  Let’s however, first understand how we can declare an Enum outside the class.

How to declare an enumeration in Java from outside the class.

enum DaysOfWeek{ // we use the enum keyword rather than class keyword

Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday;

}

public class Enum_Declare {

public static void main(String[] args) {

DaysOfWeek a = DaysOfWeek.Monday; // we do not need new keyword for the object reference

System.out.println(a);
}
}
Output:
Monday
Declaring the Enumeration in Java from within the class:
public class Enum_Declare {
enum DaysOfWeek{ // we use the Enum keyword rather than the class keyword
Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday;
}
public static void main(String[] args) {
DaysOfWeek a = DaysOfWeek.Monday; // we do not need new keyword for the object reference
System.out.println(a);
}
}
Output:
Monday

The first line within the Enum type must be the list of constants. And then we make use of the methods, constructor, and variable. And basically, the Enum is the representation of the group of constants and variables.

Please note: 

Through Enum, the type safety is improved. 

It can be used diversely through the switch case example  

We can easily traverse the Enum

The Enum comes with fields, methods, and constructors.

It in general implements the interface, though you cannot extend any of the class as it extends the Enum class internally.

And now you know how the Enum is declared in a program. Let’s now find out how we can implement it through the switch case statements.

 

Enumeration using switch case

The Enumeration value can be used for controlling the switch statement. And it’s required that each of the case statements should apply the constants from one Enum as being used by the switch statement. And the below example demonstrates the same. 

package NareshIT;
import java.util.*;
enum DaysOfWeek{ // we use the enum keyword rather than class keyword
Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday;
}


public class SwitchTest{
public static void main(String[] args) {
Switch a= DaysOfWeek.Sunday;
switch(a) { //The enumeration constants names are being used without their enumeration
case Sunday: //you can only make use of the constant defined under the Enum
System.out.println("Sunday is the Day");
break;
case Monday:
System.out.println("Monday is the day");
break;
case Tuesday:
System.out.println("Tuesday is the day");
break;
case Friday:
System.out.println("Friday is the day");
break;
}
 
Output:
Sunday is the Day 

Hope you now have got the switch statement, and how it is used in the case of the Enum. And lets now move ahead and find out what Values() and ValueOf() method are meant for, and what is the difference between them.

 

Values( ) and ValueOf( ) method

Values(): When we make an Enum, the Java compiler adds to it the values() method internally.  And this method returns an array that contains all the enum values.

Syntax:

public static enum-type[ ] values()

Now let’s return the enumeration constant that has the value equal to the string that is passed as an argument as we call the method.

Syntax:

public static enum-type valueOf (String str)

Let's now have the program for understanding the methods more elaborately

enum DaysWeek{ // we use the enum keyword rather than class keyword
Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday;
}


class DaysOfWeek {
public static void main(String args[]) {
DaysWeek a;
System.out.println("All constants of DaysWeek:");
DaysWeek A[] = DaysWeek.values(); //returns the array of constants of Enum type DaysWeek
for(DaysWeek b : A) //making use of foreach loop
System.out.println(b);
a = DaysWeek.valueOf("Sunday");
System.out.println("Its the best day:" + a);
}
}
Output:
All constants of DaysWeek:                                                                                                    
Sunday                                                                                                                        
Monday                                                                                                                        
Tuesday                                                                                                                       
Wednesday                                                                                                                     
Thursday 
Friday                                                                                                                        
Saturday                                                                                                                      
It’s the best day: Sunday

And this the way how we can make use of the Values() for returning the array which contains all the enum in the method and the Valueof() for returning the enumeration constant. Hope you now have the concept.

Now, let's move ahead and find out how the Enumeration is implemented in Java together with the constructor, method, and instance variable.

Enumeration with Constructor, instance variable, and Method

 

Generally, the Enumeration contains the constructor, and it gets executed separately for every Enum constant while the Enum class is loaded. And not merely that, an Enum can make concrete methods as well. Let’s now do the coding for understanding the implementation of the Enumeration through Constructor, instance variable, and the method.

 enum inWords
{
  One, Two, three, four;


  public String getinWord() 
  {
    switch(this) {
      case One:
        return "1";


      case Two:
        return "2";


      case three:
 return "3";


      case four:
        return "4";


      default:
        return null;
      }
   }
}
class Main
{
  public static void main(String[] args) 
  {


    // call getSize()
    // using the object One
    System.out.println("You have entered:"+inWords.One.getinWord());
  }


}
Output:
You have entered: 1

The above program needs explanation. 

Enum and Constructors: The Enum can have their constructors, and they execute separately for each of the Enum constants while the Enum class loads. And we cannot create explicitly the Enum object, and therefore we cannot directly invoke the Enum constructor.

 

Enum and methods:

We can have within the Enum both concrete methods as well as abstract methods as well. If certain Enum has an abstract method, then each of the instances of the Enum class should implement that. Remember the concrete method has a complete definition, and it can be overridden in an inherited class. If we declare it final, then it cannot be overridden. However, do not get confused with it here, as we will have a detailed blog on the methods and classes soon. You need to keep reading our blog. And for the best results, please join our java classes. You can join on-premises as well as online. So, feel free to contact us for your Java classes. 

The above Java program explains that Enum can keep up with a constructor as well as concrete methods. And an Enum keyword is used rather than a class keyword. And each of the constants in Enum calls these constructors and methods separately. And that we can see in the above program. 

 

Enum and Inheritance:

 

You need to know that Enums extends implicitly java. lang.Enum class. In java, a class extends only one parent. Hence, the same is the case with Enum.

And toString() method gets overridden in java.lang.Enum class that fetches the Enum constant name.

And Enum can have any number of interfaces.

An order does count in Enum. Through the use of the ordinal () method, we can find the index of each of the constant, just as we find the array index.

And that completes our article on the Enum. We have seen almost all the nitty-gritty of the Enum. Hope all the concepts discussed are now clear to you. Make use of the Enum whenever you have a set of constants, and you want to enumerate them and assign them index for later use inside other classes and methods. 

Naresh I Technologies is the number one computer training institute in Hyderabad and among the top five computer training institutes in India. Contact us anytime for your Java training. You can also opt for Java online training, and from any part of the world. And a big package is waiting for you. And all is yours for a nominal fee affordable for all with any range of budget. Let's have a look at what you will get with this Java training package:

  • You need to pay a nominal fee.

  • You can choose any Java certification, as per your skills and interest.

  • You have the option to select from online and classroom training.

  • A chance to study at one of the best Java training institutes in India 

  • We provide Java training in Hyderabad and USA, and no matter in which part of the world you are, you can contact us.

  • Naresh I technologies cater to one of the best Java training in India.

  • And a lot more is waiting for you.

Contact us anytime for your complete Java online training.