Java/J2EE and SOA (349 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (16 Blogs)
  • Comprehensive Java Course (4 Blogs)
  • Java/J2EE and SOA (346 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

What is Enumeration in Java? A Beginners Guide

Published on Jun 28,2019 7K Views

A tech enthusiast in Java, Image Processing, Cloud Computing, Hadoop. A tech enthusiast in Java, Image Processing, Cloud Computing, Hadoop.
45 / 72 Blog from Java Core Concepts

Enumeration is nothing but a set of named constants which helps in defining its own data types. When you can identify the type of variables in the program, it becomes easy to define them. So, Enum is used when you are already aware of all the values at the compile time. In this article, I will tell you how to define Enumeration in Java with the help of examples.

I will be covering below topics in this article:

Let’s get started!

What is Enumeration in Java?

Enumeration is basically a list of named constant. In Java, it defines a class type. It can have constructors, methods and instance variables. It is created using the enum keyword. By default, each enumeration constant is public, static and final. Even though enumeration defines a class type and has constructors, you do not need to instantiate an enum using the new variable. Enumeration variables are used and declared in the same way as that of a primitive variable.

Now let’s get into the details of Enumeration and understand its syntax and declaration.

Defining Enumeration in Java

Enum declaration can be done either outside a Class or inside a Class. But, we cannot declare Enum inside the method. Let’s take a small example to understand its declaration. First, I will tell you how to declare enum outside a class.

1. Declaring an Enumeration in Java outside a Class

enum Directions{ // enum keyword is used instead of class keyword
NORTH, SOUTH, EAST, WEST;
}
public class enumDeclaration {
public static void main(String[] args) {
Directions d1 = Directions.EAST; // new keyword is not required to create a new object reference
System.out.println(d1);
}
}

Output:

EAST

2. Declaring an Enumeration in Java inside a Class

public class enumDeclaration {
enum Directions{
NORTH, SOUTH, EAST, WEST;
}
public static void main(String[] args) {
Directions d1 = Directions.EAST; // new keyword is not required to create a new object reference
System.out.println(d1);
}
}

Output:

EAST

The first line inside the enum type should be a list of constants. Then, you can use methods, variables, and constructor. Basically, enum represents a group of variables and constants.

Note: 

  • Enum basically improves type safety.
  • It can be diversely used in switch case examples.
  • Enum can be easily traversed.
  • The enum has fields, constructors and methods.
  • Enum basically implements many interfaces but, cannot extend any class because it internally extends Enum class.

Now that you know how to declare and use enum in your program, let’s understand how to implement this with switch case statements.

Enumeration using the Switch statement

Enumeration value can also be used to control a switch statement. It is necessary that all the case statements must use constants from the same enum as used by the switch statement. Below example demonstrates the same.

package Edureka;
import java.util.*;
enum Directions {
NORTH,
SOUTH,
EAST,
WEST
}
public class Test1{
public static void main(String[] args) {
Directions d= Directions.SOUTH;
switch(d) { //The name of the enumertion constants are used without their enumeration
case NORTH: //only constants defined under enum Directions can be used
System.out.println("North direction");
break;
case SOUTH:
System.out.println("South direction");
break;
case EAST:
System.out.println("East directiion");
break;
case WEST:
System.out.println("West directiion");
break;
}

 

Output:

South Direction

I hope you understood how to implement a switch statement using an enum. Now let’s move further and understand what is Values( ) and ValueOf( ) method and the difference between them.

Values( ) and ValueOf( ) method

Values(): When you create an enum, the Java compiler internally adds the values() method. This method returns an array containing all the values of the enum.

Syntax:

public static enum-type[ ] values()

ValueOf(): This method is used to return the enumeration constant whose value is equal to the string passed as an argument while calling this method.

Syntax:

public static enum-type valueOf (String str)

Now let’s write a program to understand these methods in a more detailed manner.

enum Colors{
black, red blue, pink, white
}
class Test {
public static void main(String args[]) {
Colors c;
System.out.println("All constants of enum type Colors are:");
Colors cArray[] = Colors.values(); //returns an array of constants of type Colors
for(Colors a : cArray) //using foreach loop
System.out.println(a);
c = Colors.valueOf("red");
System.out.println("I Like" + c);
}
}

Output:

All constants of enum type Colors are:
black
red
blue
pink
white
I Like red

That’s how you can use Values() method to return the array that contains all the enum present in the method and Valueof() to return the enumeration constant. I hope you understood this concept.

Now let’s move further and understand the implementation of Enumeration in Java with the constructor, instance variable and method.

Enumeration with Constructor, instance variable and Method

Basically, Enumeration can contain constructor and it is executed separately for each enum constant at the time of enum class loading. Not just that, an enum can create concrete methods also. Let’s write a code to understand the Enumeration implementation with Constructor, instance variable and Method.

enum Student {
mack(11), Birdie(10), Son(13), Victor(9);
private int age; //variable defined in enum Student
int getage { return age; } //method defined in enum Student
public Student(int age) //constructor defined in enum
{ this.age= age; }
}
class EnumDemo {
public static void main( String args[] ) {
Student S;
System.out.println("Age of Victor is " +Student.Victor.getage()+ "years");
}
}

Output:

Age of Victor is 9 years

Here, as soon as we declare an enum variable(Student S), the constructor is called once, and it initializes the age parameter for every enumeration constant with values specified with them in parenthesis. So, that’s how it works.

This brings us to the end of the article on Enumeration in Java.  I hope you found it informative.

Check out the Java Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. We are here to help you with every step on your journey, for becoming a besides this java interview questions, we come up with a curriculum which is designed for students and professionals who want to be a Java Developer. 

Got a question for us? Please mention it in the comments section of this “Enumeration in Java ”article and we will get back to you as soon as possible.

Upcoming Batches For Java Course Online
Course NameDateDetails
Java Course Online

Class Starts on 28th September,2024

28th September

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

What is Enumeration in Java? A Beginners Guide

edureka.co