Java Enum Tutorial: Ten Examples Of Enum Inwards Java

What is Enum inwards Java
Enum inwards Java is a keyword, a characteristic which is used to stand upwardly for fixed number of well-known values inwards Java, For example, Number of days inwards Week, Number of planets inwards Solar organisation etc. Enumeration (Enum) inwards Java was introduced inwards JDK 1.5 in addition to it is i of my favorite features of J2SE v amid Autoboxing in addition to unboxing , Generics, varargs in addition to 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 in addition to handles several issues related to thread-safety in addition to Serialization automatically. By the way, Java Enum every bit a type is to a greater extent than suitable to stand upwardly for good known fixed laid of things in addition to state,  for instance representing the country 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 in addition to C++, but eventually, Java realized in addition to introduced Enum on JDK v (Tiger) yesteryear keyword Enum

In this Java Enum tutorial, nosotros volition run across different Enum instance inwards Java in addition to acquire using Enum inwards Java. Focus of this Java Enum tutorial volition live on different features provided yesteryear Enum inwards Java in addition to how to occupation them. 

If you lot guide hold used Enumeration earlier inwards C or C++ in addition to then you lot volition non live uncomfortable alongside Java Enum but inwards my opinion, Enum inwards Java is to a greater extent than rich in addition to versatile than inwards whatever other language. 

By the way, if you lot similar to acquire novel concepts using mass in addition to then you lot tin every bit good run across Head First Java s Edition, I had followed this mass piece learning Enum, when Java 1.5 was start launched. This mass has first-class chapter non exclusively on Enum but every bit good on key features of Java 1.5 and  worth reading.





How to stand upwardly for enumerable value without Java enum

 a characteristic which is used to stand upwardly for fixed number of good Java Enum Tutorial: 10 Examples of Enum inwards Javafinal constant to replicate enum similar behavior. Let’s run across an Enum instance inwards Java to sympathise the concept better. In this example, nosotros volition occupation the U.S.A. Currency Coin every bit enumerable which has values similar PENNY (1) NICKLE (5), DIME (10), in addition to 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; you lot tin assign whatever valid int value to currency e.g. 99 though at that spot is no money to stand upwardly for that value.


 2) No Meaningful Printing: printing value of whatever of these constant volition impress its numeric value instead of meaningful scream 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 cast scream e.g. CurrencyDenom.PENNY instead of but 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 in addition to has their ain namespace. Now let's run across the same instance using Enum inwards Java:

public enum Currency {PENNY, NICKLE, DIME, QUARTER};
 
Here Currency is our enum in addition to PENNY, NICKLE, DIME, QUARTER are enum constants. Notice curly braces but about enum constants because Enum is a type similar class and interface inwards Java. Also, nosotros guide hold followed the similar naming convention for enum similar cast in addition to interface (first missive of the alphabet inwards Caps) in addition to since Enum constants are implicitly static final nosotros guide 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 in addition to on to a greater extent than item term Java Enum is a type similar cast in addition to interface in addition to tin live used to define a laid of Enum constants. 

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

Since enum is a keyword you lot tin non occupation every bit a variable scream in addition to since its exclusively introduced inwards JDK 1.5 all your previous code which has an enum every bit a variable scream volition non operate in addition to 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 in addition to 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 run across an instance of using coffee enum inwards switch statement inwards this coffee enum tutorial.

4) Adding novel constants on Enum inwards Java is slow in addition to you lot tin add together novel constants without breaking the existing code.



Important points almost Enum inwards Java

1) Enums inwards Java are type-safe in addition to has their ain namespace. It agency your enum volition guide hold a type for instance "Currency" inwards below instance in addition to 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 in addition to variables within coffee Enum which makes it to a greater extent than powerful than Enum inwards C in addition to C++ every bit shown inwards adjacent 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 operate you lot demand to define a fellow member variable in addition to a constructor because PENNY (1) is genuinely calling a constructor which accepts int value, run across 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 alongside each money you lot tin define a populace getValue() method within Java enum similar whatever normal Java class. Also, the semicolon inwards the start business is optional.


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

Currency.PENNY = Currency.DIME;

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

 
 
5) Enum inwards coffee tin live used every bit an declaration on switch statement in addition to alongside "case:" similar int or char primitive type. This characteristic of coffee enum makes them really useful for switch operations. Let’s run across 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 vii 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 acquire to a greater extent than almost pros in addition to 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 fellowship they guide hold listed inwards Enum in addition to 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 fellowship is precisely the same as defined fellowship inwards the Enum.


8) In Java, Enum tin override methods also. Let’s run across 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 packet to support Java Enum. These classes are a high-performance implementation of Map in addition to Set interface inwards Java and nosotros should occupation this whenever at that spot is whatever opportunity.

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

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


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

12) Enum inwards Java tin implement the interface in addition to override whatever method similar normal cast It’s every bit good worth noting that Enum inwards coffee implicitly implements both Serializable and Comparable interface. Let's run across in addition to 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 in addition to tin every bit good provide a different implementation for different instances of enum inwards java.  Let’s run across 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 guide hold the different color nosotros made the color() method abstract in addition to permit each instance of Enum to define  their ain color. You tin acquire color of whatever money yesteryear but 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, conduct in addition to capabilities of Enumeration type inwards Java. I know, it's non slow to retrieve all those powerful features in addition to that's why I guide hold prepared this small-scale Microsoft powerpoint slide containing all of import properties of Enum inwards Java. You tin ever come upwardly dorsum in addition to cheque this slide to revise of import features of Java Enum.

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


 

Real globe Examples of Enum inwards Java

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

I think some existent globe examples of enum volition practise a lot of proficient to many pepole in addition to 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 thus many wages over traditional implementation using cast e.g. built-in Serialization, guarantee that Singleton volition ever live Singleton in addition to many more. I propose you lot to cheque my article almost Why Enum every bit Singelton is amend 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 proficient candidate to implement the Strategy interface in addition to define private strategy. By keeping all related Strategy inwards i place, Enum offering amend maintainence support. It every bit good doesn't intermission the opened upwardly unopen blueprint regulation every bit per se because whatever fault volition live detected at compile time. See this tutorial to acquire how to implement Strategy pattern using Enum inwards Java.


Enum every bit replacement of Enum String or int pattern
There is forthwith no demand to occupation String or integer constant to stand upwardly for fixed laid of things e.g. condition of object similar ON in addition to OFF for a push clit or START, IN PROGRESS in addition to DONE for a Task. Enum is much amend suited for those needs every bit it provide compile fourth dimension type security in addition to amend 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 country in addition to given input. Since Enum tin implement interface in addition to 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 guide hold non mentioned almost the valueOf method of enum inwards Java, which is used to convert String to enum inwards Java.

Here is what he has suggested, cheers @ Anonymous
“You could every bit good include valueOf() method of enum inwards coffee which is added yesteryear compiler inwards whatever enum along alongside values() method. Enum valueOf() is a static method which takes a string declaration in addition to tin live used to convert a String into an enum. One think though you lot would similar to conk 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 almost ordinal() in addition to 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 especial Enum constant.” name() method tin every bit good live used for converting Enum to String inwards Java.


That’s all on Java enum, Please portion if you lot guide hold whatever prissy tips on enum inwards Java  in addition to permit us know how you lot are using coffee enum inwards your work. You tin every bit good follow some proficient advice for using Enum yesteryear Joshua Bloch inwards his all fourth dimension classic mass 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 acquire to a greater extent than almost this cool feature, I propose reading next books. Books are i of the best resources to completely sympathise whatever theme in addition to I personally follow them every bit well. Enumeration types chapter from Thinking inwards Java is especially useful.

 a characteristic which is used to stand upwardly for fixed number of good Java Enum Tutorial: 10 Examples of Enum inwards Java
The lastly mass is suggested yesteryear i of our reader @Anonymous, you lot tin run across his comment
Check out the book, Java vii Recipes. Chapter iv contains some proficient content on Java enums. They genuinely conk into depth in addition to the examples are excellent.

Some Java Tutorials you lot May Like
The existent deviation betwixt EnumMap in addition to HashMap inwards Java


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



Sumber https://javarevisited.blogspot.com/

0 Response to "Java Enum Tutorial: Ten Examples Of Enum Inwards Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel