Java Enum Tutorial: Ten Examples Of Enum Inwards Java

What is Enum inward Java
Enum inward Java is a keyword, a characteristic which is used to correspond fixed number of well-known values inward Java, For example, Number of days inward Week, Number of planets inward Solar organisation etc. Enumeration (Enum) inward Java was introduced inward JDK 1.5 as well as it is 1 of my favorite features of J2SE v amidst Autoboxing as well as unboxing , Generics, varargs as well as static import. One of the mutual utilization of Enum which emerged inward recent years is Using Enum to write Singleton inward Java, which is past times 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 illustration representing the land of Order every bit NEW, PARTIAL FILL, FILL or CLOSED.

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

In this Java Enum tutorial, nosotros volition encounter different Enum illustration inward Java as well as acquire using Enum inward Java. Focus of this Java Enum tutorial volition live on different features provided past times Enum inward Java as well as how to utilization them. 

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

By the way, if you lot similar to acquire novel concepts using mass as well as then you lot tin likewise encounter Head First Java 2d Edition, I had followed this mass spell learning Enum, when Java 1.5 was offset launched. This mass has fantabulous chapter non solely on Enum but likewise 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 inward Javafinal constant to replicate enum similar behavior. Let’s encounter an Enum illustration inward Java to sympathize the concept better. In this example, nosotros volition utilization U.S. 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 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 topographic point 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 shout 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 bird shout e.g. CurrencyDenom.PENNY instead of simply using PENNY though this tin likewise live achieved past times using static import inward JDK 1.5

Java Enum is the reply of all this limitation. Enum inward Java is type-safe, provides meaningful String names as well as has their ain namespace. Now let's encounter the same illustration using Enum inward 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 roughly enum constants because Enum is a type similar class and interface inward Java. Also, nosotros receive got followed the similar naming convention for enum similar bird as well as interface (first alphabetic character inward Caps) as well as since Enum constants are implicitly static final nosotros receive got used all caps to specify them similar Constants inward Java.



What is Enum inward Java

Now dorsum to primary questions “What is Enum inward java” uncomplicated answer Enum is a keyword inward java as well as on to a greater extent than exceptional term Java Enum is a type similar bird 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 1 time created. Enum inward 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 utilization every bit a variable shout as well as since its solely introduced inward JDK 1.5 all your previous code which has an enum every bit a variable shout volition non function as well as needs to live refactored.


Benefits of using Enums inward 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, dissimilar the populace static lastly variables used inward Enum int pattern as well as Enum String pattern.

2) Enum has its ain namespace.

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

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



Important points virtually Enum inward Java

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


2) Enum inward 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 inward C as well as C++ every bit shown inward side past times side illustration of Java Enum type.


3) You tin specify values of enum constants at the creation time every bit shown inward 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 inward java must live private any other access modifier volition effect inward 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 inward the offset business is optional.


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

Currency.PENNY = Currency.DIME;

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

 
 
5) Enum inward 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 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 vii onwards you lot tin likewise String inward Switch illustration inward Java code.


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

Currency usCoin = Currency.DIME; if(usCoin == Currency.DIME){   System.out.println("enum inward 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 you lot are non convinced than you lot should read this article to acquire to a greater extent than virtually pros as well as cons of comparison ii enums using equals() vs == operator inward Java. 


7) Java compiler automatically generates static values() method for every enum inward java. Values() method returns array of Enum constants inward the same club they receive got listed inward Enum as well as you lot tin utilization values() to iterate over values of Enum  inward Java every bit shown inward 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 club is precisely the same as defined club inward the Enum.


8) In Java, Enum tin override methods also. Let’s encounter an illustration of overriding toString() method inside Enum inward 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 inward Java and nosotros should utilization this whenever at that topographic point is whatever opportunity.

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

If Enum has less than 64 constants than EnumSet uses RegularEnumSet bird 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 as well as then 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 past times using novel operator inward Java because the constructor of Enum inward Java tin solely live private as well as Enums constants tin solely live created within Enums itself.


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

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


13) You tin define abstract methods within Enum inward Java as well as tin likewise provide a different implementation for different instances of enum inward java.  Let’s encounter an example of using abstract method within enum inward 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 receive got the different color nosotros made the color() method abstract as well as allow each instance of Enum to define  their ain color. You tin acquire color of whatever money past times simply calling the color() method every bit shown inward below illustration 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 inward Java. I know, it's non tardily to recall all those powerful features as well as that's why I receive got prepared this modest Microsoft powerpoint slide containing all of import properties of Enum inward Java. You tin ever come upwards dorsum as well as banking concern 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 inward Java


 

Real globe Examples of Enum inward Java

So far you lot receive got learned what Enum tin exercise for you lot inward Java. You learned that enum tin live used to correspond good known fixed laid of constants,  enum tin implement interface, it tin live used inward switch illustration similar int, brusque as well as String as well as Enum has hence many useful built-in metods similar values(), vlaueOf(), name(), as well as ordinal(), but nosotros didn't acquire where to utilization the Enum inward Java? 

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


Enum every bit Thread Safe Singleton
One of the most pop utilization of Java Enum is to impelment the Singleton blueprint pattern inward Java. In fact, Enum is the easieset way to create a thread-safe Singleton inward Java. It offering hence many wages over traditional implementation using bird e.g. built-in Serialization, guarantee that Singleton volition ever live Singleton as well as many more. I advise you lot to banking concern check my article virtually Why Enum every bit Singelton is ameliorate inward Java to larn to a greater extent than on this topic. 


Strategy Pattern using Enum
You tin likewise implement the Strategy blueprint pattern using Enumeration type inward Java. Since Enum tin implement interface, it's a proficient candidate to implement the Strategy interface as well as define private strategy. By keeping all related Strategy inward 1 place, Enum offering ameliorate maintainence support. It likewise doesn't interruption the opened upwards shut 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 inward Java.


Enum every bit replacement of Enum String or int pattern
There is instantly no demand to utilization 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 ameliorate suited for those needs every bit it provide compile fourth dimension type security as well as ameliorate debugging assistent than String or Integer.


Enum every bit State Machine
You tin likewise utilization Enum to impelment State machine inward Java. 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 utilization it every bit State machine inward Java. See this tutorial from Peter Lawrey for a working example.



Enum Java valueOf example
One of my readers pointed out that I receive got non mentioned virtually the valueOf method of enum inward Java, which is used to convert String to enum inward Java.

Here is what he has suggested, cheers @ Anonymous
“You could likewise include valueOf() method of enum inward coffee which is added past times compiler inward 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 continue inward take away heed is that valueOf(String) method of enum volition throw "Exception inward thread "main" java.lang.IllegalArgumentException: No enum const class" if you lot provide whatever string other than enum values.

Another of my reader suggested virtually 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 inward enum spell name()of Enum returns the exact string which is used to create that exceptional Enum constant.” name() method tin likewise live used for converting Enum to String inward Java.


That’s all on Java enum, Please portion if you lot receive got whatever prissy tips on enum inward Java  as well as allow us know how you lot are using coffee enum inward your work. You tin likewise follow some proficient advice for using Enum past times Joshua Bloch inward 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 virtually this cool feature, I advise reading next books. Books are 1 of the best resources to completely sympathize whatever topic as well as I personally follow them every bit well. Enumeration types chapter from Thinking inward Java is especially useful.

 a characteristic which is used to correspond fixed number of good Java Enum Tutorial: 10 Examples of Enum inward Java
The lastly mass is suggested past times 1 of our reader @Anonymous, you lot tin encounter his comment
Check out the book, Java vii Recipes. Chapter four contains some proficient content on Java enums. They genuinely buy the farm into depth as well as the examples are excellent.

Some Java Tutorials you lot May Like
The existent deviation betwixt EnumMap as well as HashMap inward Java


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


Belum ada Komentar untuk "Java Enum Tutorial: Ten Examples Of Enum Inwards Java"

Posting Komentar

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel