What is Enum in Java
Now back to primary questions “What is Enum in java” simple answer Enum is a keyword in java and on more detail term Java Enum is 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 there value once created. Enum in Java provides type-safety and can be used inside switch statment like int variables. Since enum is a keyword you can not use as variable name and since its only introduced in JDK 1.5 all your previous code which has enum as variable name will not work and needs to be re-factored.Benefits of Enums in Java:
1) Enum is type-safe you can not assign anything else other than predefined Enum constants to an Enum variable. It is compiler error to assign something else unlike the public static final variables used in Enum int pattern and Enum String pattern.2) Enum has its own name-space.
3) Best feature of Enum is you can use Enum in Java inside Switch statement like int or char primitive data type.we will also see example of using java enum in switch statement in this java enum tutorial.
4) Adding new constants on Enum in Java is easy and you can add new constants without breaking existing code.
Important points about Enum in Java
1) Enums in Java are type-safe and has there own name-space. It means your enum will have a type for example "Currency" in 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 type like class or interface and 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.
3) You can specify values of enum constants at the creation time as shown in 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 which accepts int value , see below example.
public enum Currency {
PENNY(1), NICKLE(5), DIME(10), QUARTER(25);
private int value;
private Currency(int value) {
this.value = value;
}
}; Constructor of enum in java must be private any other access modifier will result in 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 semi colon in the first line is optional.
4) Enum constants are implicitly static and final and can not be changed once created. For example below code of java enum will result in compilation error:
Currency.PENNY = Currency.DIME;
The final field EnumExamples.Currency.PENNY cannot be re assigned.5) Enum in java can be used as an argument on switch statment 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.
6) Since constants defined inside Enum in Java are final you can safely compare them using "==" equality operator as shown in 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.
for(Currency coin: Currency.values()){
System.out.println("coin: " + coin);
}And it will print:
coin: PENNY
coin: NICKLE
coin: DIME
coin: QUARTERNotice the order its exactly same with defined order in enums.
8) In Java Enum can override methods also. Let’s see an example of overriding toString() method inside Enum in Java to provide 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: 109) Two new collection classes EnumMap and EnumSet are added into collection package to support Java Enum. These classes are high performance implementation of Map and Set interface in Java and we should use this whenever there is any opportunity.
10) You can not create instance of enums by using new operator in Java because constructor of Enum in Java can only be private and Enums constants can only be created inside Enums itself.
11) Instance of Enum in Java is created when any Enum constants are first called or referenced in code.
12) Enum in Java can implement the interface and override any method like normal class It’s also worth noting that Enum in java implicitly implement both Serializable and Comparable interface. Let's see and example of how to implement 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");
}
}13) You can define abstract methods inside Enum in Java and can also provide 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 implements Runnable{
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 different color we made the color() method abstract and let each instance of Enum to define there own color. You can get color of any coin by just calling color() method as shown in below example of java enum:
System.out.println("Color: " + Currency.DIME.color());
Enum Java valueOf example
One of my reader pointed out that I have not mention about valueOf method of enum in Java, which is used to convert String to enum in java. Here is what he has suggested, thanks @ 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 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 position of a 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 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. Those advice will give you more idea of using this powerful feature of Java programming language
