Java Enum Tutorial: Ten Examples Of Enum Inward Java

What is Enum inwards Java
Enum inwards Java is a keyword, a characteristic which is used to stand upwards for fixed number of well-known values inwards Java, For example, Number of days inwards Week, Number of planets inwards Solar arrangement etc. Enumeration (Enum) inwards Java was introduced inwards JDK 1.5 too it is i of my favorite features of J2SE v amidst Autoboxing too unboxing , Generics, varargs too static import. One of the mutual utilization of Enum which emerged inwards recent years is Using Enum to write Singleton inwards Java, which is yesteryear far easiest way to implement Singleton too handles several issues related to thread-safety too Serialization automatically. By the way, Java Enum equally a type is to a greater extent than suitable to stand upwards for good known fixed laid of things too state,  for illustration representing the the world of Order equally 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 too C++, but eventually, Java realized too introduced Enum on JDK v (Tiger) yesteryear keyword Enum

In this Java Enum tutorial, nosotros volition encounter different Enum illustration inwards Java too larn using Enum inwards Java. Focus of this Java Enum tutorial volition live on different features provided yesteryear Enum inwards Java too how to utilization them. 

If y'all direct hold used Enumeration earlier inwards C or C++ too therefore y'all volition non live uncomfortable amongst Java Enum but inwards my opinion, Enum inwards Java is to a greater extent than rich too versatile than inwards whatsoever other language. 

By the way, if y'all similar to larn novel concepts using majority too therefore y'all tin besides encounter Head First Java s Edition, I had followed this majority spell learning Enum, when Java 1.5 was starting fourth dimension launched. This majority has fantabulous chapter non alone on Enum but besides on key features of Java 1.5 and  worth reading.





How to stand upwards for enumerable value without Java enum

 a characteristic which is used to stand upwards for fixed number of good Java Enum Tutorial: 10 Examples of Enum inwards Javafinal constant to replicate enum similar behavior. Let’s encounter an Enum illustration inwards Java to sympathize the concept better. In this example, nosotros volition utilization United States of America Currency Coin equally enumerable which has values similar PENNY (1) NICKLE (5), DIME (10), too 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 role it has some serious limitations:

 1) No Type-Safety: First of all it’s non type-safe; y'all tin assign whatsoever valid int value to currency e.g. 99 though at that topographic point is no money to stand upwards for that value.


 2) No Meaningful Printing: printing value of whatsoever of these constant volition impress its numeric value instead of meaningful scream of money e.g. when y'all impress NICKLE it volition impress "5" instead of "NICKLE"


3) No namespace: to access the currencyDenom constant nosotros demand to prefix course of education scream e.g. CurrencyDenom.PENNY instead of merely using PENNY though this tin besides 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 too has their ain namespace. Now let's encounter the same illustration using Enum inwards Java:

public enum Currency {PENNY, NICKLE, DIME, QUARTER};
 
Here Currency is our enum too PENNY, NICKLE, DIME, QUARTER are enum constants. Notice curly braces merely about 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 course of education too interface (first missive of the alphabet inwards Caps) too 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” unproblematic answer Enum is a keyword inwards java too on to a greater extent than exceptional term Java Enum is a type similar course of education too interface too tin live used to define a laid of Enum constants. 

Enum constants are implicitly static too final too y'all tin non alter their value i time created. Enum inwards Java provides type-safety too tin live used within switch declaration similar int variables. 

Since enum is a keyword y'all tin non utilization equally a variable scream too since its alone introduced inwards JDK 1.5 all your previous code which has an enum equally a variable scream volition non move too needs to live refactored.


Benefits of using Enums inwards Java


1) Enum is type-safe y'all tin non assign anything else other than predefined Enum constants to an Enum variable. It is a compiler fault to assign something else, dissimilar the populace static lastly variables used inwards Enum int pattern too Enum String pattern.

2) Enum has its ain namespace.

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

4) Adding novel constants on Enum inwards Java is tardily too y'all tin add together novel constants without breaking the existing code.



Important points virtually Enum inwards Java

1) Enums inwards Java are type-safe too has their ain namespace. It agency your enum volition direct hold a type for illustration "Currency" inwards below illustration too y'all tin non assign whatsoever 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 y'all tin define constructor, methods too variables within coffee Enum which makes it to a greater extent than powerful than Enum inwards C too C++ equally shown inwards side yesteryear side illustration of Java Enum type.


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

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

But for this to move y'all demand to define a fellow member variable too 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 upshot inwards compilation error. Now to acquire the value associated amongst each money y'all tin define a populace getValue() method within Java enum similar whatsoever normal Java class. Also, the semicolon inwards the starting fourth dimension work 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 upshot inwards compilation error:

Currency.PENNY = Currency.DIME;

The lastly patch EnumExamples.Currency.PENNY cannot live reassigned.

 
 
5) Enum inwards coffee tin live used equally an declaration on switch statement too amongst "case:" similar int or char primitive type. This characteristic of coffee enum makes them rattling useful for switch operations. Let’s encounter an illustration of how to utilization 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 y'all tin besides String inwards Switch instance inwards Java code.


6) Since constants defined within Enum inwards Java are lastly y'all tin safely compare them using "==", the equality operator equally shown inwards next illustration 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 utilization equals() method or compareTo() method to compare Objects.

If y'all are non convinced than y'all should read this article to larn to a greater extent than virtually pros too 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 gild they direct hold listed inwards Enum too y'all tin utilization values() to iterate over values of Enum  inwards Java equally 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 gild is precisely the same as defined gild inwards the Enum.


8) In Java, Enum tin override methods also. Let’s encounter an illustration 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 bundle to support Java Enum. These classes are a high-performance implementation of Map too Set interface inwards Java and nosotros should utilization this whenever at that topographic point is whatsoever opportunity.

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

If Enum has less than 64 constants than EnumSet uses RegularEnumSet course of education which internally uses a long variable to shop those 64 Enum constants too if Enum has to a greater extent than keys than 64 too therefore it uses JumboEnumSet. See my article the difference betwixt RegularEnumSet too 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 alone live private too Enums constants tin alone live created within Enums itself.


11) An instance of Enum inwards Java is created when whatsoever Enum constants are starting fourth dimension called or referenced inwards code.

12) Enum inwards Java tin implement the interface too override whatsoever method similar normal course of education It’s besides worth noting that Enum inwards coffee implicitly implements both Serializable and Comparable interface. Let's encounter too illustration 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 too tin besides 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 illustration since every money volition direct hold the different color nosotros made the color() method abstract too allow each instance of Enum to define  their ain color. You tin acquire color of whatsoever money yesteryear merely calling the color() method equally shown inwards below illustration of Java Enum:

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

So that was the comprehensive listing of properties, demeanour too capabilities of Enumeration type inwards Java. I know, it's non tardily to scream back all those powerful features too that's why I direct hold prepared this minor Microsoft powerpoint slide containing all of import properties of Enum inwards Java. You tin e'er come upwards dorsum too banking concern check this slide to revise of import features of Java Enum.

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


 

Real globe Examples of Enum inwards Java

So far y'all direct hold learned what Enum tin exercise for y'all inwards Java. You learned that enum tin live used to stand upwards for good known fixed laid of constants,  enum tin implement interface, it tin live used inwards switch instance similar int, curt too String too Enum has therefore many useful built-in metods similar values(), vlaueOf(), name(), too ordinal(), but nosotros didn't larn where to utilization the Enum inwards Java? 

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


Enum equally Thread Safe Singleton
One of the most pop utilization 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 therefore many payoff over traditional implementation using course of education e.g. built-in Serialization, guarantee that Singleton volition e'er live Singleton too many more. I advise y'all to banking concern check my article virtually Why Enum equally Singelton is amend inwards Java to larn to a greater extent than on this topic. 


Strategy Pattern using Enum
You tin besides implement the Strategy blueprint pattern using Enumeration type inwards Java. Since Enum tin implement interface, it's a expert candidate to implement the Strategy interface too define private strategy. By keeping all related Strategy inwards i place, Enum offering amend maintainence support. It besides doesn't interruption the opened upwards unopen blueprint regulation equally per se because whatsoever fault volition live detected at compile time. See this tutorial to larn how to implement Strategy pattern using Enum inwards Java.


Enum equally replacement of Enum String or int pattern
There is at i time no demand to utilization String or integer constant to stand upwards for fixed laid of things e.g. condition of object similar ON too OFF for a push clit or START, IN PROGRESS too DONE for a Task. Enum is much amend suited for those needs equally it provide compile fourth dimension type security too amend debugging assistent than String or Integer.


Enum equally State Machine
You tin besides utilization Enum to impelment State machine inwards Java. Influenza A virus subtype H5N1 State machine transition to predifine laid of states based upon electrical flow the world too given input. Since Enum tin implement interface too override method, y'all tin utilization it equally 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 virtually the valueOf method of enum inwards Java, which is used to convert String to enum inwards Java.

Here is what he has suggested, thank y'all @ Anonymous
“You could besides include valueOf() method of enum inwards coffee which is added yesteryear compiler inwards whatsoever enum along amongst values() method. Enum valueOf() is a static method which takes a string declaration too tin live used to convert a String into an enum. One think though y'all would similar to cash inwards one's chips on inwards hear is that valueOf(String) method of enum volition throw "Exception inwards thread "main" java.lang.IllegalArgumentException: No enum const class" if y'all furnish whatsoever string other than enum values.

Another of my reader suggested virtually ordinal() too name() utility method of Java enum Ordinal method of Java Enum returns the seat of a Enum constant equally they declared inwards enum spell name()of Enum returns the exact string which is used to create that exceptional Enum constant.” name() method tin besides live used for converting Enum to String inwards Java.


That’s all on Java enum, Please portion if y'all direct hold whatsoever dainty tips on enum inwards Java  too allow us know how y'all are using coffee enum inwards your work. You tin besides follow some expert advice for using Enum yesteryear Joshua Bloch inwards his all fourth dimension classic majority Effective Java. That advice volition give y'all to a greater extent than thought of using this powerful characteristic of Java programming language


Further Reading on Java Enum
If y'all similar to larn to a greater extent than virtually this cool feature, I advise reading next books. Books are i of the best resources to completely sympathize whatsoever topic too I personally follow them equally well. Enumeration types chapter from Thinking inwards Java is peculiarly useful.

 a characteristic which is used to stand upwards for fixed number of good Java Enum Tutorial: 10 Examples of Enum inwards Java
The lastly majority is suggested yesteryear i of our reader @Anonymous, y'all tin encounter his comment
Check out the book, Java seven Recipes. Chapter four contains some expert content on Java enums. They genuinely cash inwards one's chips into depth too the examples are excellent.

Some Java Tutorials y'all May Like
The existent departure betwixt EnumMap too HashMap inwards Java


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


Komentar

Postingan populer dari blog ini

2 Ways To Banking Concern Tally If A String Is Rotation Of Other Inward Java?

How To Convert String To Integer To String Inward Coffee Amongst Example

How To Induce Chrome, Firefox Blurry, Over Bright, Fading Afterwards Windows Ten Update