Showing posts with label Java Enum. Show all posts
Showing posts with label Java Enum. Show all posts

Wednesday, December 11, 2019

2 Ways To Impress Custom String Value Of Coffee Enum

We all know that how powerful enumeration type inwards Java is, in addition to 1 of the principal forcefulness of enum is that they tin implement an interface, they tin accept an instance variable in addition to y'all tin likewise override whatsoever method within enum instance. In Java programs, nosotros ofttimes demand to convert Enum to String type, sometimes but to impress values inwards log file in addition to other fourth dimension for storing log into database.  By default, when y'all impress an enum constant, it impress its literal value e.g. if get upward of enum instance is RED, in addition to then it volition impress RED. This is likewise the value which is returned past times name() method of java.lang.Enum class. But, at that spot are situations when nosotros desire a custom String value for enum constant. For example, I desire to impress Red instead of RED when I convert Enum to String. How exercise y'all exercise that? Well, at that spot are 2 ways y'all tin accomplish this, commencement past times overriding toString() method for each enum constant in addition to instant past times using an instance variable to concord custom String value. You tin render custom value spell creating Enum constants in addition to after y'all tin telephone phone that method which returns custom  String value. In this article, nosotros volition run into instance of these 2 ways.



Java Program to impress custom String values to Enum inwards Java

As I said at that spot are 2 ways y'all tin associate a user-defined String value to an enum constant
  • By overriding toString() method
  • By Using an instance variable

In our example, nosotros accept an enumeration type called Color, it has 3 enum constants RED, GREEN,  and BLUE.  By default when y'all travel past times whatsoever of these enumeration constants to System.out.println() method, it volition telephone phone toString() method of java.lang.Object. Since every enum past times default extends java.lang.Enum, which overrides toString() method.




As shown inwards next code snippet, this overridden version returns the ame, which is the literal value of enumeration constant.

   /**      * Returns the get upward of this enum constant, equally contained inwards the      * declaration.  This method may endure overridden, though it typically      * isn't necessary or desirable.  An enum type should override this      * method when a to a greater extent than "programmer-friendly" string cast exists.      *      * @return the get upward of this enum constant      */     public String toString() {         return name;     }

You tin run into the overnice advice given their inwards cast of Javadoc comments. It clearly suggests that y'all should override toString() method inwards enum if y'all demand to a greater extent than "programmer-friendly" string. Another agency to render a custom String is to shop that value on a fellow member value in addition to render it past times creating a custom method, scream back y'all cannot exercise toString()  but tin for certain exercise getCustomString(). Now y'all may think what is the divergence betwixt these 2 approach? Well, at that spot is a pregnant difference. First agency is genuinely the correct agency to render custom String value because toString() is criterion method for such task. Many framework in addition to other method e.g. print() in addition to println() method from System class, calls this method when y'all travel past times an enum. You don't acquire this awesome characteristic amongst whatsoever other method. Actually instant agency is extension of associating a custom value amongst enum, which could endure integer, String or anything else. In our program, ColorWithToString overrides toString() to render custom String value and ColorWithSpecificString uses an instance variable to concord a specific String value.  here is amount code instance :
 We all know that how powerful enumeration type inwards Java is 2 Ways to Print Custom String Value of Java Enum


/**  * Couple of ways to render custom String values to whatsoever enum instance inwards Java.  *  * @author Javin Paual  */ public class EnumWithCustomString{      public static void main(String args[]) {          System.out.println("Default String value of Java Enum Color.RED is "                 + Color.RED);         System.out.println("Custom String value of Java Enum  ColorWithToString.RED is "                 + ColorWithToString.RED);         System.out.println("Custom String value of Enum inwards Java, ColorWithSpecificString.RED is "                 + ColorWithSpecificString.RED.getCustomString());     }      /*      * If y'all don't implement toString() method inwards Enum      * constants, toString() volition render their get upward e.g.      * RED.toString() volition render RED. This is also      * same equally calling RED.name() method.      */     private enum Color {          RED, GREEN, BLUE;     }      /*      * You tin implement toString() method within each enum      * constant to render a custom String value. For example      * inwards below instance RED.toString() volition render "Red"      */     private enum ColorWithToString {          RED {                      @Override                     public String toString() {                         return "Red";                     }                 },         GREEN {                      @Override                     public String toString() {                         return "Green";                     }                 },         BLUE {                      @Override                     public String toString() {                         return "Blue";                     }                 };     }       /*      * You tin likewise render custom String values for Java enum, by      * storing them inwards divide field. In this instance toString() will      * stay unchanged, but y'all tin acquire custom String value past times calling      * your method e.g. RED.toString() volition render RED, but RED.getCustomString()      * volition render "Red".      */     private enum ColorWithSpecificString {          RED("red"), BLUE("blue"), GREEN("green");          private String custom;          private ColorWithSpecificString(String custom) {             this.custom = custom;         }          public String getCustomString() {             return custom;         }      }  }   Output: Default String value of Java Enum Color.RED is RED Custom String value of Java Enum  ColorWithToString.RED is Red Custom String value of Enum inwards Java, ColorWithSpecificString.RED is red

That's all nigh how to impress custom string value of enum inwards Java. As suggested past times Oracle Java developer's equally well, the correct agency to render an String other than literal value is past times overriding toString() method. This method is meant to render a String value in addition to used past times many developers to convert an Enum to String equally well. Second method likewise highlight, how y'all tin purpose enum equally amount blown class, defining instance variable, creating methods in addition to writing code there. You tin purpose this technique to associate anything amongst your enum constant inwards Java.

Further Learning
Data Structures in addition to Algorithms: Deep Dive Using Java
here)
  • Difference betwixt RegularEnumSet in addition to JumboEnumSet inwards Java (read here)
  • What Every Java Programmer Should know nigh Enum (click here)
  • 10 points nigh Enum inwards Java (see here)
  • Learn how to purpose Enum inwards Java amongst a Simple Example (check here)
  • Can Enum accept Constructor inwards Java (learn here)
  • Can nosotros purpose Enum inwards Switch Statement inwards Java (Yes)
  • How to purpose valueOf method of Enum (check here)
  • How to loop over Enum constants inwards Java (example)
  • Java tip to convert  Enum to String inwards Java (see tip)
  • String to Enum inwards Java amongst Example (check here)
  • Saturday, November 9, 2019

    Java Enum Tutorial - X Things Coffee Devs Should Know Most Using Enum

    Apart from the Class as well as Interface, Enumeration type or Enum is roughly other pop type inwards Java programming language. Enum allows y'all to correspond a fixed number of well-known things inwards a type-safe fashion e.g. days of the week, days of the month, planets inwards solar system, buttons on remote control, keys on keyboard as well as suits on playing cards. Before Enum was introduced, prior to Java 1.5, integer and string constants are used to correspond the fixed number of things, known equally enum int pattern as well as enum string pattern equally described inwards classic Effective Java past times none other than Joshua Bloch. Though they served the purpose, they had roughly major drawbacks which resulted inwards wretched character code.


    One of the major issues was type-safety i.e. y'all cannot confine them to correspond a fixed number of values e.g. an integer constant, which is representing days of the calendar week tin give the axe accept value equally 100, which is incorrect, given nosotros accept exclusively vii days inwards a week.

    These limitations are addressed past times providing enum type, which guarantees that exclusively right as well as fixed number of values tin give the axe live on assigned to them. The skilful affair virtually Enum inwards Java is that they are characteristic rich, the bad affair is that they are notwithstanding under-used as well as many developers don't fifty-fifty know virtually Enumeration type inwards detail.

    Though at that topographic point is a lot of weblog post virtually unlike features of Enum inwards Java, as well as their usage, at that topographic point is hardly whatsoever page, which provides a skilful hold off at key points virtually Enum. It doesn't hateful to live on comprehensive but at-least provides those lesser known details.

    I had previously shared roughly features inwards shape of question-answer on my article 15 Java Enum Interview Questions as well as inwards this post, nosotros volition larn to a greater extent than virtually Enum inwards Java inwards this article. I accept kept the explanation curt as well as to the indicate to it may hold off similar a summary as well as notes than a tutorial, but tin give the axe live on really useful to speedily acquire up-to-speed alongside Enum type inwards Java.




    Enum Tutorial inwards Java

    1. Enum is constants inwards Java. They are implicitly declared public, static and final. Since they are constant, at that topographic point is no way y'all tin give the axe alter them.


    2. All enumeration type implicitly extends from java.lang.Enum course of report internally. Which way Enums are internally represented equally a course of report type. Furthermore, enum constants are instances of the enumeration class.

    There is a lot of similarity betwixt enum as well as class in Java but at that topographic point is likewise roughly divergence e.g. enum instances are implicitly public static final, y'all don't remove to declare them, equally explained in The Complete Java Masterclass and shown inwards the next slide :

     Enumeration type or Enum is roughly other pop type inwards Java programming linguistic communication Java Enum Tutorial - 10 Things Java Devs Should Know virtually Using Enum




    3. Since all Enum type extends java.lang.Enum, they cannot extend whatsoever other course of report inwards Java, equally multiple inheritances are non allowed inwards Java, as well as a course of report tin give the axe exclusively extend i class. This holding has non changed fifty-fifty alongside the introduction of default or defender methods inwards Java 8, which allows y'all to declare non-abstract methods inwards the interface.


    4. Enum tin give the axe implement an interface inwards Java, which is likewise a way to extend enum type. When an Enum extend an interface, each of their instance implement interface method inwards their ain way or y'all tin give the axe render a default implementation nether Enum course of report itself.

    Take a hold off at this example, it's non the best but at-least demonstrate how to implement interface within enum inwards Java.

    public class EnumDemo04{          public static void main(String args[]) {                  EnumThread thread = EnumThread.ONE;                 thread.run();                  thread = EnumThread.TWO;                 thread.run();                  thread = EnumThread.THREE;                 thread.run();          }                   private enum EnumThread implements Runnable{              ONE {                 @Override                 public void run() {                        System.out.println("ONE");                 }             },              TWO {                 @Override                 public void run() {                        System.out.println("TWO");                 }             },              THREE;                  @Override                 public void run() {             System.out.println("Default");                  }         } }  Output ONE TWO Default 

    You tin give the axe run into that EnumThread, which is an enum truly implements Runnable interface as well as likewise overrides run() method. This proves that enumeration type cannot exclusively implement an interface but likewise tin give the axe override methods inwards Java. See constructor but it tin give the axe exclusively live on private. You cannot become far world because Enum instances are supposed to live on created at compile fourth dimension as well as from the course of report itself.

    H5N1 non-private Enum constructor alongside whatsoever modifier other than somebody is a compile-time fault inwards Java. Though a constructor without whatsoever access modifier is likewise allowed.

    Similarly, y'all tin give the axe likewise overload constructor within Enum, equally shown below, past times the way, don't forget to declare enum constants or; earlier declaring constructors, y'all tin give the axe likewise run into this post to larn to a greater extent than virtually Enum constructor inwards Java.

    public enum EnumWithConstructor{                  ;                 private EnumWithConstructor(){                         System.out.println("Default no-arg Enum                                           constructor");                 }                               EnumWithConstructor(int i){                         System.out.println("Enum Constructor alongside i argument");                 }                          // compile fourth dimension fault - illegal access modifier,                  // exclusively somebody is allowed                 public EnumWithConstructor(String s){                         System.out.println("public constructor                            are non allowed within Enum inwards Java");                 }  }



    6. The java.lang.Enum defines several useful methods, which is available to all enumeration type inwards Java. You tin give the axe exercise name() method to acquire the advert of whatsoever Enum constants. String literal used to write enum constants are their name.

    Similarly, values() method tin give the axe live on used to acquire an array of all Enum constants from an Enum type as well as y'all tin give the axe exercise valueOf() method to convert whatsoever String to Enum constant inwards Java, equally shown below

    public class EnumDemo06{          public static void main(String args[]) {                 Gender fromString =  Gender.valueOf("MALE");                 System.out.println("Gender.MALE.name() : "                          + fromString.name());         }                private enum Gender{                 MALE, FEMALE;         }  }  Output: Gender.MALE.name() : MALE

    In this code snippet, valueOf() method returns an Enum constant Gender.MALE, calling advert on that returns "MALE".



    7.  There are ii ways to compare enum constants inwards Java, y'all tin give the axe either exercise equals() method or only == operator. There are roughly advantages of using == operator over equals, equally it provides type-safety as well as likewise avoids potential NullPointerException if the enum on which y'all are calling equals() is null. You tin give the axe run into to a greater extent than details virtually comparison ii Enums inwards Java here.



    8. Enum constants cannot live on cloned inwards Java. An endeavour to brand a clone of Enum constants volition throw CloneNotSupportedException.



    9.  Like int, short and char, as well as String from Java 7, Enum tin give the axe likewise live on used within switch as well as instance statements, equally shown below. You tin give the axe likewise run into this post to larn to a greater extent than virtually Enum as well as switch instance inwards Java :

    public class EnumDemo9{                public static void main(String args[]) {                                              SmartPhone iPhone = new SmartPhone(SmartPhone.OS.iOS);                 SmartPhone.OS operatingSystem = iPhone.getOS();                                 switch(operatingSystem){                 case iOS:                         System.out.println("Running on iOS");                         break;                                       case Android:                         System.out.println("Running on Android");                         break;                  case Windows8:                         System.out.println("Running on Windows8");                         break;                 }         }   }  class SmartPhone {                 public enum OS{                 iOS, Android, Windows8;         }          private OS os;               public SmartPhone(OS os){                 this.os = os;                   }             public OS getOS(){                 return os;          } }  Output: Running on iOS
    You tin give the axe clearly say that nosotros are using an enum variable within the switch() block to conclusion making, as well as nosotros are likewise using enum constants inwards instance statements. You tin give the axe farther run into Effective Java third Edition to larn to a greater extent than virtually to a greater extent than advanced as well as effective exercise of Enum similar this.

     Enumeration type or Enum is roughly other pop type inwards Java programming linguistic communication Java Enum Tutorial - 10 Things Java Devs Should Know virtually Using Enum



    10. When y'all declare an Enum type within a class, it is past times default static. You tin give the axe run into that from to a higher house instance that, nosotros tin give the axe access OS Enum type equally SmartPhone.OS, which is similar accessing a static fellow member of whatsoever class.


    11. The new() operator is non permitted to live on used alongside enum, non fifty-fifty within enum itself. This is because, Enum constants are fixed, as well as no instance of an enum tin give the axe live on created at runtime.


    12.  Like whatsoever other class, y'all tin give the axe likewise override toString() method for whatsoever Enum type. By default toString() method returns the advert of Enum constants as well as its output is same equally of name() method, but y'all tin give the axe override it to render to a greater extent than information.


     Enumeration type or Enum is roughly other pop type inwards Java programming linguistic communication Java Enum Tutorial - 10 Things Java Devs Should Know virtually Using EnumThat's all virtually Enum inwards Java. I promise this special helps y'all to empathize Enumeration type inwards Java. It's i of the primal concept, which y'all can't afford to overlook. Since I accept used Java fifty-fifty earlier enumeration type exists, I tin give the axe say that enum helps y'all to write robust as well as produce clean code inwards Java.


    Further Learning
    The Complete Java Masterclass
    see here)
  • How to convert Enum to String in Java  (click here)
  • How to exercise enum in switch instance inwards Java (see here)
  • How to loop over Enum constants using foreach loop inwards Java (link)
  • How to exercise valueOf() method of Enum inwards Java (read here)
  • How to produce enum from String in Java (read here)
  • Practical Example of Enum inwards Java (see here)
  • How to define a constructor for Enumeration type (read here)
  • How to implement Singleton designing using Enum in Java (check here)
  • Difference betwixt RegularEnumSet as well as JumboEnumSet (read here)
  • 15 Questions to cheque your noesis virtually Enum inwards Java (answers)

  • Thanks for reading this article thence far. If y'all similar this article as well as thence delight portion alongside your friends as well as colleagues. If y'all accept whatsoever questions or feedback as well as thence delight driblet a note.