Java Enum Tutorial: 10 Examples of Enum in Java (original) (raw)
Let’s see an Enum example in Java to understand the concept better. In this example, we will use US Currency Coin as enumerable which has values like PENNY (1) NICKLE (5), DIME (10), and QUARTER (25).
public class CurrencyDenom { public static final int PENNY = 1; public static final int NICKLE = 5; public static final int DIME = 10; public static final int QUARTER = 25; }
public class Currency { private int currency; //CurrencyDenom.PENNY,CurrencyDenom.NICKLE, // CurrencyDenom.DIME,CurrencyDenom.QUARTER }
Though this can serve our purpose it has some serious limitations:
1) No Type-Safety: First of all it’s not type-safe; you can assign any valid int value to currency e.g. 99 though there is no coin to represent that value.
2) No Meaningful Printing: printing value of any of these constants will print its numeric value instead of the meaningful name of coin e.g. when you print NICKLE it will print "5" instead of "NICKLE"
3) No namespace: to access the currencyDenom constant we need to prefix class name e.g. CurrencyDenom.PENNY instead of just using PENNY though this can also be achieved by using static import in JDK 1.5
Java Enum is the answer of all these limitations. Enum in Java is type-safe, provides meaningful String names and has their own namespace. Now let's see the same example using Enum in Java:
public enum Currency {PENNY, NICKLE, DIME, QUARTER};
Here Currency is our enum and PENNY, NICKLE, DIME, QUARTER are enum constants. Notice curly braces around enum constants because Enum is a type like class and interface in Java. Also, we have followed a similar naming convention for enum like class and interface (first letter in caps) and since Enum constants are implicitly static final we have used all caps to specify them like Constants in Java.
What is Enum in Java
Now back to primary questions “What is Enum in java” simple answer Enum is a keyword in java and in more detail term Java Enum is a type like class and interface and can be used to define a set of Enum constants.
Enum constants are implicitly static and final and you can not change their value once created. Enum in Java provides type-safety and can be used inside switch statements like int variables.
Since enum is a keyword you can not use as a variable name and since it's only introduced in JDK 1.5 all your previous code which has an enum as a variable name will not work and needs to be refactored.
Benefits of using Enums in Java
Enum is type-safe you can not assign anything else other than predefined Enum constants to an Enum variable. It is a compiler error to assign something else, unlike the public static final variables used in the Enum int pattern and Enum String pattern.
Enum has its own namespace.
The best feature of Enum is you can use Enum in Java inside Switch statements like int or char primitive data type. We will also see an example of using java enum in the switch statement in this java enum tutorial.
Adding new constants on Enum in Java is easy and you can add new constants without breaking the existing code.
Important points about Enum in Java
- Enums in Java are type-safe and have their own namespace. It means your enum will have a type for example "Currency" in the below example and you can not assign any value other than specified in Enum Constants.
public enum Currency { PENNY, NICKLE, DIME, QUARTER }; Currency coin = Currency.PENNY; coin = 1; //compilation error
2**) Enum in Java are reference types** like class or interfaceand you can define constructor, methods, and variables inside java Enum which makes it more powerful than Enum in C and C++ as shown in next example of Java Enum type.
- You can specify values of enum constants at the creation time as shown in the below example:
public enum Currency {PENNY(1), NICKLE(5), DIME(10), QUARTER(25)};
But for this to work you need to define a member variable and a constructor because PENNY (1) is actually calling a constructor that accepts int value, see the below example.
public enum Currency { PENNY(1), NICKLE(5), DIME(10), QUARTER(25); private int value;
private Currency(int value) {
this.value = value;
}
};
The constructor of the enum in java must be private any other access modifier will result in a compilation error. Now to get the value associated with each coin you can define a public getValue() method inside Java enum like any normal Java class. Also, the semicolon in the first line is optional.
- Enum constants are implicitly static and final and can not be changed once created. For example, the below code of java enum will result in a compilation error:
Currency.PENNY = Currency.DIME;
The final field EnumExamples.Currency.PENNY cannot be reassigned.
- Enum in java can be used as an argument on switch statement and with "case:" like int or char primitive type. This feature of java enum makes them very useful for switch operations. Let’s see an example of how to use java enum inside switch statement:
Currency usCoin = Currency.DIME;
switch (usCoin) {
case PENNY:
System.out.println("Penny coin");
break;
case NICKLE:
System.out.println("Nickle coin");
break;
case DIME:
System.out.println("Dime coin");
break;
case QUARTER:
System.out.println("Quarter coin");
}
from JDK 7 onwards you can also String in Switch case in Java code.
- Since constants defined inside Enum in Java are final you can safely compare them using "==", the equality operator as shown in the following example of Java Enum:
Currency usCoin = Currency.DIME; if(usCoin == Currency.DIME){ System.out.println("enum in java can be compared using =="); }
By the way comparing objects using == operator is not recommended, Always use equals() method or compareTo() method to compare Objects.
If you are not convinced then you should read this article to learn more about the pros and cons of comparing two enums using equals() vs == operator in Java.
- Java compiler automatically generates static values() method for every enum in java. Values() method returns an array of Enum constants in the same order they have listed in Enum and you can use values() to iterate over values of Enum in Java as shown in the below example:
for(Currency coin: Currency.values()){ System.out.println("coin: " + coin); }
And it will print:
coin: PENNY coin: NICKLE coin: DIME coin: QUARTER
Notice the order is exactly the same as the defined order in the Enum.
- In Java, Enum can override methods also. Let’s see an example of overriding the toString() method inside Enum in Java to provide a meaningful description for enums constants.
public enum Currency { ........
@Override public String toString() { switch (this) { case PENNY: System.out.println("Penny: " + value); break; case NICKLE: System.out.println("Nickle: " + value); break; case DIME: System.out.println("Dime: " + value); break; case QUARTER: System.out.println("Quarter: " + value); } return super.toString(); } };
And here is how it looks like when displayed:
Currency usCoin = Currency.DIME; System.out.println(usCoin);
Output: Dime: 10
- Two new collection classes EnumMap and EnumSet are added to the collection package to support Java Enum. These classes are a high-performance implementation of the Map and Set interface in Java and we should use this whenever there is an opportunity.
EnumSet doesn't have any public constructor instead it provides factory methods to create instances e.g. EnumSet.of() methods. This design allows EnumSet to internally choose between two different implementations depending upon the size of Enum constants.
If Enum has less than 64 constants then EnumSet uses RegularEnumSet class which internally uses a long variable to store those 64 Enum constants and if Enum has more keys than 64 then it uses JumboEnumSet. See my article on the difference between RegularEnumSet and JumboEnumSet for more details.
You can not create an instance of enums by using a new operator in Java because the constructor of Enum in Java can only be private and Enums constants can only be created inside Enums itself.
An instance of Enum in Java is created when any Enum constants are first called or referenced in code.
Enum in Java can implement the interface and override any method like a normal class It’s also worth noting that Enum in java implicitly implements both Serializable and Comparable interfaces. Let's see an example of how to implement the interface using Java Enum:
public enum Currency implements Runnable{ PENNY(1), NICKLE(5), DIME(10), QUARTER(25); private int value; ............
@Override public void run() { System.out.println("Enum in Java implement interfaces");
} }
- You can define abstract methods inside Enum in Java and can also provide a different implementation for different instances of enum in java. Let’s see an example of using abstract method inside enum in java
public enum Currency { PENNY(1) { @Override public String color() { return "copper"; } }, NICKLE(5) { @Override public String color() { return "bronze"; } }, DIME(10) { @Override public String color() { return "silver"; } }, QUARTER(25) { @Override public String color() { return "silver"; } }; private int value;
public abstract String color();
private Currency(int value) {
this.value = value;
}
}
In this example since every coin will have a different color we made the color() method abstract and let each instance of Enum define its own color. You can get the color of any coin by just calling the color() method as shown in the below example of Java Enum:
System.out.println("Color: " + Currency.DIME.color());
So that was the comprehensive list of properties, behavior, and capabilities of Enumeration type in Java. I know, it's not easy to remember all those powerful features and that's why I have prepared this small Microsoft PowerPoint slide containing all important properties of Enum in Java. You can always come back and check this slide to revise important features of Java Enum.
Real-world Examples of Enum in Java
So far you have learned what Enum can do for you in Java. You learned that enum can be used to represent well known fixed set of constants, enum can implement an interface, it can be used in switch cases like int, short and String and Enum has so many useful built-in methods like values(), the valueOf(), name(), and ordinal(), but we didn't learn where to use the Enum in Java?
I think some real-world examples of enum will do a lot of good to many people and that's why I am going to summarize some of the popular usages of Enum in the Java world below.
Enum as Thread Safe Singleton
One of the most popular uses of Java Enum is to implement the Singleton design pattern in Java. In fact, Enum is the easiest way to create a thread-safe Singleton in Java. It offers so many advantages over traditional implementation using class e.g. built-in Serialization, guarantee that Singleton will always be Singleton, and many more. I suggest you check my article about Why Enum as Singelton is better in Java to learn more on this topic.
Strategy Pattern using Enum
You can also implement the Strategy design pattern using the Enumeration type in Java. Since Enum can implement an interface, it's a good candidate to implement the Strategy interface and define individual strategy.
By keeping all related Strategies in one place, Enum offers better maintenance support. It also doesn't break the open-closed design principle as per se because any error will be detected at compile time. See this tutorial to learn how to implement Strategy patterns using Enum in Java.
Enum as replacement of Enum String or int pattern
There is now no need to use String or integer constant to represent a fixed set of things e.g. status of an object like ON and OFF for a button or START, IN PROGRESS, and DONE for a Task. Enum is much better suited for those needs as it provides compile-time type safety and a better debugging assistant than String or Integer.
Enum as State Machine
You can also use Enum to implement a State machine in Java. A State machine transitions to a predefined set of states based upon the current state and given input. Since Enum can implement an interface and override method, you can use it as a State machine in Java. See this tutorial from Peter Lawrey for a working example.
Enum Java valueOf example
One of my readers pointed out that I have not mentioned the valueOf method of enum in Java, which is used to convert String to enum in Java.
Here is what he has suggested, thanks to @ Anonymous
“You could also include valueOf() method of enum in java which is added by compiler in any enum along with values() method. Enum valueOf() is a static method which takes a string argument and can be used to convert a String into an enum. One think though you would like to keep in mind is that valueOf(String) method of enum will throw "Exception in thread "main" java.lang.IllegalArgumentException: No enum const class" if you supply any string other than enum values.
Another of my reader suggested about ordinal() and name() utility method of Java enum Ordinal method of Java Enum returns the position of an Enum constant as they declared in enum while name()of Enum returns the exact string which is used to create that particular Enum constant.” name() method can also be used for converting Enum to String in Java.
That’s all on Java enum, Please share if you have any nice tips on an enum in Java and let us know how you are using java enum in your work. You can also follow some good advice for using Enum by Joshua Bloch in his all-time classic book Effective Java. That advice will give you more idea of using this powerful feature of the Java programming language