Sotirios-Efstathios Maneas

About Sotirios-Efstathios Maneas

Sotirios-Efstathios (Stathis) Maneas is a postgraduate student at the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. His main interests include distributed systems, web crawling, model checking, operating systems, programming languages and web applications.

Java Enumeration example

In this tutorial we will discuss about enumerations in Java. The Java programming language contains the enum keyword, which represents a special data type that enables for a variable to belong to a set of predefined constants. The variable must be equal to one of the values that have been predefined for it.

The values defined inside an enum are constants and shall be typed in uppercase letters. Also, these values are implicitly static and final and cannot be changed, after their declaration. If an enum is a member of a class, then it is implicitly defined as static. Finally, you should use an enum, when you need to define and represent a fixed set of constants.

 
The most common example of a simple enum includes the days of the week, as shown below:

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

Enums in Java are type-safe and thus, the value of an enum variable must be one of the predefined values of the enum itself. Also, enums have their own namespace and they can be used in a switch statement, in the same way as integers.

Furthermore, enums in Java are considered to be reference types, like class or Interface and thus, a programmer can define constructor, methods and variables, inside an enum.

In addition, a programmer can specify values of enum constants at their creation time, as shown in the example below:

public enum Day {
	SUNDAY(1),
	MONDAY(2),
	TUESDAY(3),
	WEDNESDAY(4),
	THURSDAY(5),
	FRIDAY(6),
	SATURDAY(7)
}

However, in order for this approach to function properly, a private member variable and a private constructor must be defined, as shown below:

private int value;
	
private Day(int value) {
	this.value = value;
}

In order to retrieve the value of each constant of the enum, you can define a public method inside the enum:

public int getValue() {
	return this.value;
}

As we already mentioned, the values inside an enum are constants and thus, you can use them in comparisons using the equals or compareTo methods.

The Java Compiler automatically generates a static method for each enum, called values. This method returns an array of all constants defined inside the enum:

//Printing all constants of an enum.
for(Day day: Day.values())
	System.out.println(day.name());

Notice that the values are returned in the same order as they were initially defined.

Methods: name, valueOf and toString

An enum contains the name and valueOf methods. The valueOf method can be used to map from a name to the corresponding enum constant, while the name method returns the name of an enum’s constant, exactly as declared in its declaration. Also, an enum can override the toString method, just like any other Java class. A simple example is shown below:

@Override
public String toString() {
	switch(this) {
		case FRIDAY:
			return "Friday: " + value;
		case MONDAY:
			return "Monday: " + value;
		case SATURDAY:
			return "Saturday: " + value;
		case SUNDAY:
			return "Sunday: " + value;
		case THURSDAY:
			return "Thursday: " + value;
		case TUESDAY:
			return "Tuesday: " + value;
		case WEDNESDAY:
			return "Wednesday: " + value;
		default:
			return null;
	}
}

An enum in Java can implement an Interface or extend a class, just like any other normal class. Also, an enum implicitly implements both the Serializable and Comparable interfaces.

Finally, you can define abstract methods inside an enum in Java. Each constant of the enum implements each abstract method independently. For example:

Car.java:

public enum Car {
	AUDI {
		@Override
		public int getPrice() {
			return 25000;
		}
	},
	MERCEDES {
		@Override
		public int getPrice() {
			return 30000;
		}
	},
	BMW {
		@Override
		public int getPrice() {
			return 20000;
		}
	};
	
	public abstract int getPrice();
}

The EnumMap and EnumSet Collections

An EnumMap is a specialized Map implementation. All of the keys in an EnumMap must come from a single enum type that is specified, explicitly or implicitly, when the map is created. EnumMaps are represented internally as arrays. Also, EnumMaps are maintained in the natural order of their keys.

A sample example that uses an EnumMap is shown below:

EnumMapExample.java:

import java.util.EnumMap;

public class EnumMapExample {
	public static void main(String[] args) {
		// Create an EnumMap that contains all constants of the Car enum.
		EnumMap cars = new EnumMap(Car.class);
		
		// Put some values in the EnumMap.
		cars.put(Car.BMW, Car.BMW.getPrice());
		cars.put(Car.AUDI, Car.AUDI.getPrice());
		cars.put(Car.MERCEDES, Car.MERCEDES.getPrice());
		
		// Print the values of an EnumMap.
		for(Car c: cars.keySet())
			System.out.println(c.name());
		
		System.out.println(cars.size());
		
		// Remove a Day object.
		cars.remove(Car.BMW);
		System.out.println("After removing Car.BMW, size: " + cars.size());
		
		// Insert a Day object.
		cars.put(Car.valueOf("BMW"), Car.BMW.getPrice());
		System.out.println("Size is now: " + cars.size());
	}
}

A sample execution is shown below:

AUDI
MERCEDES
BMW
3
After removing Car.BMW, size: 2
Size is now: 3

An EnumSet is a specialized Set implementation. All of the elements in an EnumSet must come from a single enum type that is specified, explicitly or implicitly, when the set is created. EnumSet are represented internally as bit vectors. Also, an iterator traverses the elements in their natural order.

A sample example that uses an EnumSet is shown below:

EnumSetExample.java:

import java.util.EnumSet;

public class EnumSetExample {
	public static void main(String[] args) {
		// Create an EnumSet that contains all days of the week.
		EnumSet week = EnumSet.allOf(Day.class);
		
		// Print the values of an EnumSet.
		for(Day d: week)
			System.out.println(d.name());
		
		System.out.println(week.size());
		
		// Remove a Day object.
		week.remove(Day.FRIDAY);
		System.out.println("After removing Day.FRIDAY, size: " + week.size());
		
		// Insert a Day object.
		week.add(Day.valueOf("FRIDAY"));
		System.out.println("Size is now: " + week.size());
	}
}

A sample execution is shown below:

SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
7
After removing Day.FRIDAY, size: 6
Size is now: 7

Download the Eclipse Project

The Eclipse project of this example: EnumExample.zip.

 
This was a tutorial about enums in Java.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close