Java Enum Tutorial: X Examples Of Enum Inwards Java

Advertisement

Masukkan script iklan 970x90px

Java Enum Tutorial: X Examples Of Enum Inwards Java

Jumat, 15 Januari 2021

What is Enum inwards Java
Enum inwards Java is a keyword, a characteristic which is used to correspond fixed number of well-known values inwards Java, For example, Number of days inwards Week, Number of planets inwards Solar organization etc. Enumeration (Enum) inwards Java was introduced inwards JDK 1.5 as well as it is i of my favorite features of J2SE v amidst Autoboxing as well as unboxing , Generics, varargs as well as static import. One of the mutual occupation of Enum which emerged inwards recent years is Using Enum to write Singleton inwards Java, which is yesteryear far easiest way to implement Singleton as well as handles several issues related to thread-safety as well as Serialization automatically. By the way, Java Enum every bit a type is to a greater extent than suitable to correspond good known fixed laid of things as well as state,  for instance representing the land of Order every bit NEW, PARTIAL FILL, FILL or CLOSED.

Enumeration(Enum) was non originally available inwards Java though it was available inwards some other linguistic communication similar C as well as C++, but eventually, Java realized as well as introduced Enum on JDK v (Tiger) yesteryear keyword Enum

In this Java Enum tutorial, nosotros volition encounter different Enum instance inwards Java as well as larn using Enum inwards Java. Focus of this Java Enum tutorial volition live on different features provided yesteryear Enum inwards Java as well as how to occupation them. 

If you lot direct hold used Enumeration earlier inwards C or C++ thence you lot volition non live uncomfortable amongst Java Enum but inwards my opinion, Enum inwards Java is to a greater extent than rich as well as versatile than inwards whatever other language. 

By the way, if you lot similar to larn novel concepts using majority thence you lot tin every bit good encounter Head First Java 2d Edition, I had followed this majority piece learning Enum, when Java 1.5 was origin launched. This majority has fantabulous chapter non solely on Enum but every bit good on key features of Java 1.5 and  worth reading.





How to correspond enumerable value without Java enum

 a characteristic which is used to correspond fixed number of good Java Enum Tutorial: 10 Examples of Enum inwards Javafinal constant to replicate enum similar behavior. Let’s encounter an Enum instance inwards Java to empathize the concept better. In this example, nosotros volition occupation US of America Currency Coin every bit enumerable which has values similar PENNY (1) NICKLE (5), DIME (10), as well as 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 tin serve our occupation it has some serious limitations:

 1) No Type-Safety: First of all it’s non type-safe; you lot tin assign whatever valid int value to currency e.g. 99 though at that spot is no money to correspond that value.


 2) No Meaningful Printing: printing value of whatever of these constant volition impress its numeric value instead of meaningful holler of money e.g. when you lot impress NICKLE it volition impress "5" instead of "NICKLE"


3) No namespace: to access the currencyDenom constant nosotros demand to prefix class holler e.g. CurrencyDenom.PENNY instead of simply using PENNY though this tin every bit good live achieved yesteryear using static import inwards JDK 1.5

Java Enum is the reply of all this limitation. Enum inwards Java is type-safe, provides meaningful String names as well as has their ain namespace. Now let's encounter the same instance using Enum inwards Java:

public enum Currency {PENNY, NICKLE, DIME, QUARTER};
 
Here Currency is our enum as well as PENNY, NICKLE, DIME, QUARTER are enum constants. Notice curly braces closed to enum constants because Enum is a type similar class and interface inwards Java. Also, nosotros direct hold followed the similar naming convention for enum similar class as well as interface (first missive of the alphabet inwards Caps) as well as since Enum constants are implicitly static final nosotros direct hold used all caps to specify them similar Constants inwards Java.



What is Enum inwards Java

Now dorsum to primary questions “What is Enum inwards java” elementary answer Enum is a keyword inwards java as well as on to a greater extent than item term Java Enum is a type similar class as well as interface as well as tin live used to define a laid of Enum constants. 

Enum constants are implicitly static as well as final as well as you lot tin non alter their value i time created. Enum inwards Java provides type-safety as well as tin live used within switch declaration similar int variables. 

Since enum is a keyword you lot tin non occupation every bit a variable holler as well as since its solely introduced inwards JDK 1.5 all your previous code which has an enum every bit a variable holler volition non function as well as needs to live refactored.


Benefits of using Enums inwards Java


1) Enum is type-safe you lot tin non assign anything else other than predefined Enum constants to an Enum variable. It is a compiler fault to assign something else, different the populace static concluding variables used inwards Enum int pattern as well as Enum String pattern.

2) Enum has its ain namespace.

3) The best characteristic of Enum is you tin occupation Enum inwards Java within Switch statement similar int or char primitive information type. We volition every bit good encounter an instance of using coffee enum inwards switch statement inwards this coffee enum tutorial.

4) Adding novel constants on Enum inwards Java is tardily as well as you lot tin add together novel constants without breaking the existing code.



Important points close Enum inwards Java

1) Enums inwards Java are type-safe as well as has their ain namespace. It way your enum volition direct hold a type for instance "Currency" inwards below instance as well as you lot tin non assign whatever value other than specified inwards Enum Constants.
 
public enum Currency { PENNY, NICKLE, DIME, QUARTER }; Currency money = Currency.PENNY; money = 1; //compilation fault  


2) Enum inwards Java are reference types like class or interface and you lot tin define constructor, methods as well as variables within coffee Enum which makes it to a greater extent than powerful than Enum inwards C as well as C++ every bit shown inwards side yesteryear side instance of Java Enum type.


3) You tin specify values of enum constants at the creation time every bit shown inwards below example:

public enum Currency {PENNY(1), NICKLE(5), DIME(10), QUARTER(25)};

But for this to function you lot demand to define a fellow member variable as well as a constructor because PENNY (1) is genuinely calling a constructor which accepts int value, encounter 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 enum inwards java must live private any other access modifier volition number inwards compilation error. Now to acquire the value associated amongst each money you lot tin define a populace getValue() method within Java enum similar whatever normal Java class. Also, the semicolon inwards the origin occupation is optional.


4) Enum constants are implicitly static and final and tin non live changed i time created. For example, below code of coffee enum volition number inwards compilation error:

Currency.PENNY = Currency.DIME;

The concluding land EnumExamples.Currency.PENNY cannot live reassigned.

 
 
5) Enum inwards coffee tin live used every bit an declaration on switch statement as well as amongst "case:" similar int or char primitive type. This characteristic of coffee enum makes them real useful for switch operations. Let’s encounter an instance of how to occupation coffee enum within 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 seven onwards you lot tin every bit good String inwards Switch instance inwards Java code.


6) Since constants defined within Enum inwards Java are concluding you lot tin safely compare them using "==", the equality operator every bit shown inwards next instance of  Java Enum:

Currency usCoin = Currency.DIME; if(usCoin == Currency.DIME){   System.out.println("enum inwards coffee tin live compared using =="); }

By the way comparison objects using == operator is non recommended, Always occupation equals() method or compareTo() method to compare Objects.

If you lot are non convinced than you lot should read this article to larn to a greater extent than close pros as well as cons of comparison 2 enums using equals() vs == operator inwards Java. 


7) Java compiler automatically generates static values() method for every enum inwards java. Values() method returns array of Enum constants inwards the same social club they direct hold listed inwards Enum as well as you lot tin occupation values() to iterate over values of Enum  inwards Java every bit shown inwards below example:

for(Currency coin: Currency.values()){    System.out.println("coin: " + coin); }

And it volition print:
coin: PENNY coin: NICKLE coin: DIME coin: QUARTER
               
Notice the social club is just the same as defined social club inwards the Enum.


8) In Java, Enum tin override methods also. Let’s encounter an instance of overriding toString() method inside Enum inwards 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 hither is how it looks similar when displayed:

Currency usCoin = Currency.DIME; System.out.println(usCoin);  Output: Dime: 10


     
9) Two novel collection classes EnumMap and EnumSet are added into collection parcel to support Java Enum. These classes are a high-performance implementation of Map as well as Set interface inwards Java and nosotros should occupation this whenever at that spot is whatever opportunity.

EnumSet doesn't direct hold whatever populace constructor instead it provides mill methods to create instance e.g. EnumSet.of() methods. This blueprint allows EnumSet to internally direct betwixt 2 different implementations depending upon the size of Enum constants.

If Enum has less than 64 constants than EnumSet uses RegularEnumSet class which internally uses a long variable to shop those 64 Enum constants as well as if Enum has to a greater extent than keys than 64 thence it uses JumboEnumSet. See my article the difference betwixt RegularEnumSet as well as JumboEnumSet for to a greater extent than details.



10) You tin non create an instance of enums yesteryear using novel operator inwards Java because the constructor of Enum inwards Java tin solely live private as well as Enums constants tin solely live created within Enums itself.


11) An instance of Enum inwards Java is created when whatever Enum constants are origin called or referenced inwards code.

12) Enum inwards Java tin implement the interface as well as override whatever method similar normal class It’s every bit good worth noting that Enum inwards coffee implicitly implements both Serializable and Comparable interface. Let's encounter as well as instance 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 inwards Java implement interfaces");                     } }


13) You tin define abstract methods within Enum inwards Java as well as tin every bit good provide a different implementation for different instances of enum inwards java.  Let’s encounter an example of using abstract method within enum inwards 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 instance since every money volition direct hold the different color nosotros made the color() method abstract as well as permit each instance of Enum to define  their ain color. You tin acquire color of whatever money yesteryear simply calling the color() method every bit shown inwards below instance of Java Enum:

System.out.println("Color: " + Currency.DIME.color());

So that was the comprehensive listing of properties, behaviour as well as capabilities of Enumeration type inwards Java. I know, it's non tardily to holler back all those powerful features as well as that's why I direct hold prepared this pocket-size Microsoft powerpoint slide containing all of import properties of Enum inwards Java. You tin ever come upwardly dorsum as well as depository fiscal establishment check this slide to revise of import features of Java Enum.

 a characteristic which is used to correspond fixed number of good Java Enum Tutorial: 10 Examples of Enum inwards Java


 

Real globe Examples of Enum inwards Java

So far you lot direct hold learned what Enum tin practise for you lot inwards Java. You learned that enum tin live used to correspond good known fixed laid of constants,  enum tin implement interface, it tin live used inwards switch instance similar int, curt as well as String as well as Enum has thence many useful built-in metods similar values(), vlaueOf(), name(), as well as ordinal(), but nosotros didn't larn where to occupation the Enum inwards Java? 

I think some existent globe examples of enum volition practise a lot of skillful to many pepole as well as that's why I am going to summarize some of the pop usage of Enum inwards Java globe below. 


Enum every bit Thread Safe Singleton
One of the most pop occupation of Java Enum is to impelment the Singleton blueprint pattern inwards Java. In fact, Enum is the easieset way to create a thread-safe Singleton inwards Java. It offering thence many payoff over traditional implementation using class e.g. built-in Serialization, guarantee that Singleton volition ever live Singleton as well as many more. I propose you lot to depository fiscal establishment check my article close Why Enum every bit Singelton is meliorate inwards Java to larn to a greater extent than on this topic. 


Strategy Pattern using Enum
You tin every bit good implement the Strategy blueprint pattern using Enumeration type inwards Java. Since Enum tin implement interface, it's a skillful candidate to implement the Strategy interface as well as define private strategy. By keeping all related Strategy inwards i place, Enum offering meliorate maintainence support. It every bit good doesn't interruption the opened upwardly closed blueprint regulation every bit per se because whatever fault volition live detected at compile time. See this tutorial to larn how to implement Strategy pattern using Enum inwards Java.


Enum every bit replacement of Enum String or int pattern
There is immediately no demand to occupation String or integer constant to correspond fixed laid of things e.g. condition of object similar ON as well as OFF for a push or START, IN PROGRESS as well as DONE for a Task. Enum is much meliorate suited for those needs every bit it provide compile fourth dimension type security as well as meliorate debugging assistent than String or Integer.


Enum every bit State Machine
You tin every bit good occupation Enum to impelment State machine inwards Java. Influenza A virus subtype H5N1 State machine transition to predifine laid of states based upon electrical flow land as well as given input. Since Enum tin implement interface as well as override method, you lot tin occupation it every bit State machine inwards Java. See this tutorial from Peter Lawrey for a working example.



Enum Java valueOf example
One of my readers pointed out that I direct hold non mentioned close the valueOf method of enum inwards Java, which is used to convert String to enum inwards Java.

Here is what he has suggested, thank you lot @ Anonymous
“You could every bit good include valueOf() method of enum inwards coffee which is added yesteryear compiler inwards whatever enum along amongst values() method. Enum valueOf() is a static method which takes a string declaration as well as tin live used to convert a String into an enum. One think though you lot would similar to decease on inwards take away heed is that valueOf(String) method of enum volition throw "Exception inwards thread "main" java.lang.IllegalArgumentException: No enum const class" if you lot provide whatever string other than enum values.

Another of my reader suggested close ordinal() as well as name() utility method of Java enum Ordinal method of Java Enum returns the seat of a Enum constant every bit they declared inwards enum piece name()of Enum returns the exact string which is used to create that special Enum constant.” name() method tin every bit good live used for converting Enum to String inwards Java.


That’s all on Java enum, Please part if you lot direct hold whatever overnice tips on enum inwards Java  as well as permit us know how you lot are using coffee enum inwards your work. You tin every bit good follow some skillful advice for using Enum yesteryear Joshua Bloch inwards his all fourth dimension classic majority Effective Java. That advice volition give you lot to a greater extent than thought of using this powerful characteristic of Java programming language


Further Reading on Java Enum
If you lot similar to larn to a greater extent than close this cool feature, I propose reading next books. Books are i of the best resources to completely empathize whatever topic as well as I personally follow them every bit well. Enumeration types chapter from Thinking inwards Java is peculiarly useful.

 a characteristic which is used to correspond fixed number of good Java Enum Tutorial: 10 Examples of Enum inwards Java
The lastly majority is suggested yesteryear i of our reader @Anonymous, you lot tin encounter his comment
Check out the book, Java seven Recipes. Chapter four contains some skillful content on Java enums. They genuinely decease into depth as well as the examples are excellent.

Some Java Tutorials you lot May Like
The existent departure betwixt EnumMap as well as HashMap inwards Java


Further Learning
Complete Java Masterclass
Java Fundamentals: The Java Language
Java In-Depth: Become a Complete Java Engineer!