Showing posts sorted by relevance for query enum-in-java-example-tutorial. Sort by date Show all posts
Showing posts sorted by relevance for query enum-in-java-example-tutorial. Sort by date Show all posts

Friday, November 22, 2019

Java Enum Faq - What Every Coffee Developer Should Know Most Enumeration Type

Java Enum was i of the best features added on JDK 1.5 Tiger liberate along amongst Generics, Autoboxing, in addition to varargs. Enum inwards Java represents fixed publish of well-known things e.g. publish of days inwards Week, the publish of months inwards the calendar yr etc. Unlike C in addition to C++ Enum inwards Java are much powerful in addition to they are non an integer constant, Instead, Enum is a Type similar shape or interface which provides compile fourth dimension type safety. In this Java Enum tutorial, nosotros volition run across a span of of import points close Java Enum which help to empathise Enum amend in addition to acquire most out of it. I convey written inwards the manner of FAQ i.e. ofttimes asked questions, this volition help yous to larn to a greater extent than close Java Enum's capability in addition to features e.g. whether Enum tin extend shape or implement methods or not? When yous tin override methods within enum? whether yous tin compare Enum using equals() or == inwards Java? etc


Java Enum FAQ - Frequently asked Questions

As I told yous enum or enumeration type inwards Java is i of the of import concepts inwards Java. It's non only plenty to larn close shape in addition to interface, yous besides convey to larn close Enumeration type. In this article, I volition respond or hence of the ofttimes asked questions based upon Java Enum, these volition help yous to larn the concept amend in addition to motivate yous to explore past times yourself.



What is Enum inwards Java?
Enum is Java produce much similar a shape in addition to interface which is used to stand upward for fixed publish of well-known things e.g. days of the week, months of a yr etc.


What is the role of Enum inwards Java?
As I told inwards the previous example, yous tin role Enum to stand upward for fixed publish of things e.g. yous tin role it stand upward for the states of your application e.g. threads states similar Runnable, Running, Stopped etc. You tin besides role it to implement Strategy pattern. You tin role Enum to write thread-safe Singleton, in addition to fifty-fifty to produce your ain acre automobile inwards Java. 


What is the divergence betwixt C, C++ enum in addition to Java Enum?
Unlike C in addition to C++, Enum inwards Java are non integer constant, they are classes, similar to whatever interface or class. Because of this argue Enum inwards Java provides type safety in addition to compile time checking which was non possible amongst enum int pattern. Java Enum is a full-fledged type in addition to yous tin role it equally shape or interface.



Can Enum extend a Class inwards Java?
No, Enum cannot extend a Class inwards Java. Every Enum inwards Java extends from java.lang.Enum implicitly in addition to because of this Enum tin non extend whatever other shape inwards Java.


Can Enum convey Constructor inwards Java?
Enum inwards Java doesn't convey a populace constructor. This way yous tin non produce an additional instance of Enum instances other than what is created from Enum shape itself in addition to available at compile time. Enum tin convey a private constructor, though.



Can yous declare methods within Enum inwards Java?
Yes, yous tin declare methods inwards Java Enum in addition to yous tin even override in addition to overload them within private Enum instances. For example, yous convey declared a Color enum which has a method getHexCode(). Now, yous declare 4 colors or enum constants inwards Color enum e.g. RED, BLUE, GREEN, WHITE, BLACKand in addition to hence yous tin override getHexCode() method to render hex code for these color e.g. RED volition render 0xFF0000 in addition to BLACK volition render 0x000000.

You tin farther read Core Java, Volume 1 - Fundamentals past times Cay S. Horstmann to larn to a greater extent than close advanced features of Enum inwards Java.




Can yous alter the value of Enum instance inwards Java?
Enum values or Enum instances are public, static in addition to final inwards Java. They are a compile-time constant, which way yous tin non changes values of Enum instances in addition to farther assignment volition lawsuit inwards compile fourth dimension error.


Can Enum implement an interface in addition to override method inwards Java?
Yes, Enum inwards Java tin implement interface in addition to override methods. In fact, Java Enum implicitly implements Comparable interface in addition to override compareTo() method. You tin banking company correspond the code of java.lang.Enum shape to confirm this. 


How to compare 2 Enumeration inwards Java?
Enum instance inwards Java tin last compared using == equality operator or equals() method inwards Java. Enum provides the high-quality implement for equals() in addition to hashCode in addition to tin last used inwards Set in addition to Map. But for functioning reason, it's best to role EnumMap in addition to EnumSet spell storing enum inwards Collection.


How to compare same instances of the same Enum inwards Java?
When yous compare unlike instances of the same Enum type, they are compared inwards the guild on which they are declared inwards Enum. You tin acquire this guild past times calling the ordinal() method of Enum.

 Java Enum was i of the best features added on JDK  Java Enum FAQ - What Every Java Developer should know close Enumeration type


How to convert Enum to String inwards Java?
Enum provides implicit methods similar values(), ordinal() in addition to name() which tin last used to acquire all Enum instances equally an array, guild of enum equally declared inwards shape in addition to String cite of Enum instances inwards Java.



How to convert Enum to Array inwards Java?
You tin role Enum's values() to convert an Enum to array inwards Java. This method returns an array containing all Enum constants. See these examples to larn to a greater extent than close how to role values() method of java.lang.Enum inwards Java.


How to iterate over Enum inwards Java?
You tin role Enum's values() method tin last used to iterate over enum. It returns an array which tin last traversed using whatever loop constructs inwards Java, including Java 1.5 enhanced for loop.


That's all close or hence frequently asked questions close Enumeration type inwards Java. Enum is much powerful in addition to they convey used inwards unlike ways inwards Java programming language. yous tin fifty-fifty role Enum to produce thread-safe Singleton inwards Java. You tin besides supplant your quondam code which is written using enum int blueprint or enum String blueprint inwards Java.

If yous convey whatever questions related to Enum inwards Java in addition to hence delight driblet a comment in addition to I'll elbow grease to respond your questions. If yous desire to larn to a greater extent than yous tin farther read Head First Java, it explains Enum concepts quite well. 


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

Saturday, March 28, 2020

How To Iterate Over Coffee Enum : Values() Example

Enum Values() Example
In this Java programming tutorial, nosotros volition larn how to iterate over enum inwards Java. Since Enums are a collection of a finite position out of well-known objects, ofttimes nosotros require to iterate over them. Enums are besides concluding inwards Java in addition to has a private constructor, which agency you lot tin non practice enum instances ane time declared. Iteration over Enum is extremely simple, provided you lot know well-nigh implicit values() method, which is a static method, provided past times java.lang.Enum. Since every enum inwards Java extends java.lang.Enum, they all acquire this implicit values() method. Actually in that place are duo of them, e.g. valueOf(), name(), ordinal() etc. This method returns enum constants inwards the enterprise they are declared inwards Enum class. Even the ordinal() method returns the same order.

By the way, In lastly duo of Java tutorials on enum nosotros convey seen How to convert Enum to String inwards Java, Enum valueOf Example in addition to Enum Constructor Example.

This tutorial focuses on iteration over Enum inwards Java. Remember iteration, traversing or looping over enum is same thing, in addition to thus you lot tin job this technique for whatsoever of these purpose.



How to loop over Enum inwards Java

 nosotros volition larn how to iterate over enum inwards Java How to Iterate over Java Enum :  values() ExampleIn this Java program, nosotros convey created an enum called Language, which stand upwardly for programming linguistic communication in addition to in that place rank. Our business is to iterate through this enum in addition to impress name, in addition to rank of each enum instance.



Just recall that, all enum inwards Java provides values() method, which returns an array of enum, containing all instances. Here is sum code illustration of Iterating over enum :

/**  * Java programme to iterate over enum using for loop in addition to values method.  * values() method of enum returns all enum instances every bit array for iteration.  *  * @author java67  */ public class EnumHowTo {      public enum Language{         JAVA(1), PYTHON(2), PERL(3), SCALA(4);             private int rank;                 private Language(int rank){             this.rank = rank;         }                 public int getRank(){             return rank;         }         };         public static void main(String args[]) {          System.out.println("Java Enum Iterate Example using for loop");                 for(Language pl : Language.values()){             System.out.println( pl.name() + " : " + pl.rank);         }         }      }  Output: Java Enum Iterate Example using for loop JAVA : 1 PYTHON : two PERL : iii SCALA : 4


That's all on How to iterate over enum inwards Java. As I said before in addition to you lot tin run into from this code example, its simple. Don't forget values() method, which render array of enum instances. To larn to a greater extent than well-nigh Enum inwards Java in addition to in that place usages, run into next tutorials :

Further Learning
Complete Java Masterclass
Enum Fundamental in addition to Concepts inwards Java
  • Why Enum Singletons are amend inwards Java
  • How to practice thread prophylactic Singleton inwards Java using Enum
  • Autoboxing, Generic, varargs in addition to Enum inwards Java
  • How to job Generic to write type prophylactic classes inwards Java
  • Saturday, November 9, 2019

    Java Enum Valueof Illustration - How To Operate

    valueOf Example inward Java Enum
    valueOf method of Java Enum is used to recollect Enum constant declared inward Enum Type past times passing String inward other words valueOf method is used to convert String to Enum constants. In this Java Enum valueOf instance nosotros volition come across how to role valueOf method inward Java. valueOf method is implicitly available to all Java Enum because every enum inward Java implicitly extends java.lang.Enum class. valueOf method of enum accepts just same String which is used to declare Enum constant to supply that Enum constant. valueOf method is case-sensitive as well as invalid String volition lawsuit inward IllegalArgumentException. In curt String passed to valueOf method of Java enum must last same to String returned past times name() method e.g. TrafficSigal.RED.name() returns RED as well as yous should transcend RED to valueOf() to larn TrafficSignal.RED. This volition last to a greater extent than clear volition next Java Enum valueOf example. By the agency its 3rd tutorial on Enum inward Java afterward previous ship on Java Enum Swith Example  and Java Enum toString example. If yous receive got non read those tutorial yous may honour useful.



    valueOf Java Enum Example

    Here is consummate code instance of valueOf method of Java Enum. In this enum instance nosotros receive got used a TrafficSignal Enum to demonstrate how nosotros tin dismiss recollect Enum from String inward Java.



     method of Java Enum is used to recollect Enum constant declared inward Enum Type past times passing St Java Enum ValueOf Example - How to role /**
     *
     * Java plan to demo How to role valueOf method of Enum
     * to exercise enum. This is uncomplicated Enum valueOf instance which
     * teaches how to role valueOf method.
     *
     * @author
     */

    public class EnumValueOfExample {

        public static void main(String args[]) {
                     
          //valueOf method returns Enum instance amongst advert matching to String passed to valueOf
          TrafficSignal request = TrafficSignal.valueOf("RED");
          System.out.println("name : " + signal.name() + " activeness : " + signal.getAction());
       
          //Another Enum valueOf exampel
          request = TrafficSignal.valueOf("GREEN");
          System.out.println("name : " + signal.name() + " activeness : " + signal.getAction());
       
       
          //valueOf volition throw IllegalArgumentException if nosotros transcend invalid String
          request = TrafficSignal.valueOf("Green");
        }
     
    }

    enum TrafficSignal{
        RED("stop"), GREEN("start"), ORANGE("slow down");
     
        private String action;
     
        public String getAction(){
            return this.action;
        }
        private TrafficSignal(String action){
            this.action = action;
        }
    }

    Output:
    advert : RED activeness : stop
    advert : GREEN activeness : start
    Exception inward thread "main" java.lang.IllegalArgumentException: No enum const class test.TrafficSignal.Green
            at java.lang.Enum.valueOf(Enum.java:196)
            at test.TrafficSignal.valueOf(
    EnumValueOfExample.java:34)
            at test.CollectionTest.main(EnumValueOfExample.java:29)
    Java Result: 1


    That's all on this Java Enum valueOf example. See 10 Java enum Examples for to a greater extent than examples of enum inward Java. In curt enum valueOf is a useful method which is past times default available to all enum constants as well as tin dismiss last used to larn Enum constants from String.

    Further Learning
    Complete Java Masterclass
    Java CyclicBarrier Example - Concurrency tutorial

    Tuesday, March 31, 2020

    Autoboxing, Enum, Generics, Varargs Methods - Coffee V Features Quick Overview

    What is Autoboxing , Generics, Enum in addition to Varargs method inwards Java 5
    Java five introduces Autoboxing, Generics, varargs in addition to Enum along amongst several other features in addition to improvement. It's been few years when Java programming linguistic communication was enhanced amongst these features but nonetheless Java programmer affair Autoboxing, Enum, Generics or Variable arguments equally an advanced characteristic in addition to afraid to larn them. They are really much utilisation of Java fundamentals but similar Abstraction, Inheritance, Encapsulation in addition to Polymorphism are utilisation of Object oriented programming concepts. It's of import to empathize what are these characteristic in addition to How to utilisation them, fifty-fifty if y'all don't utilisation them inwards your code, y'all may create got to last on individual else code which is written inwards Java five in addition to uses Generics Collection, Autoboxing quite frequently. In this Java five tutorial, nosotros volition come across the brief overview of Java five features similar Generics, Enum, Autoboxing in addition to unboxing in addition to variable arguments methods along amongst examples in addition to explanations.



    What is Autoboxing inwards Java
    First starts amongst Autoboxing characteristic of Java 5 which allows a programmer to forget nearly converting primitive to wrapper shape code. Autoboxing agency Java compiler volition automatically convert primitive to object wherever necessary.

    For example, if y'all are writing a method which accepts an int declaration in addition to y'all are passing an Integer object, Unlike previous Java version,  Java compiler volition non throw any compile fourth dimension error, Instead, it volition convert Integer to int past times using unboxing inwards Java.

    On the other hand, if method appear a Double Object equally an declaration in addition to y'all exceed double primitive hence Java volition convert primitive to a Double object using Autoboxing inwards Java. See What is Autoboxing inwards Java - Example corner cases  for to a greater extent than information in addition to detailed instance of how to utilisation autoboxing inwards Java.

    One of the points which is worth noting spell using autoboxing inwards Java five code is non mixing primitive amongst an object spell comparison amongst equals objects, this may give y'all unpredictable results, come across What is the work spell using "==" amongst autoboxing inwards Java 5 for consummate details  on actual problem.




    What is Generics inwards Java
    Generics is closed to other high-value add-on inwards Java programming linguistic communication added on JDK 5. Generics provides compile fourth dimension type-safety in addition to reducing run a peril on ClassCastException in Java. By using Generics inwards Java, y'all tin notice type-safety related fault compile timer rather than acquire them at runtime. You tin likewise utilisation Generics wildcards inwards Java to write improve type-safe API methods. Generics industrial plant on the regulation of type-erasure, which erases all type information during compile time. for to a greater extent than details come across How Generics industrial plant inwards Java. If y'all are preparing for whatsoever Java five interview in addition to looking for closed to interview questions on Generics, hence this listing of Java Generics inquiry volition aid y'all to prepare better.

    What is Enum inwards Java
    Enum is a way to stand upwards for fixed laid of well-known values inwards Java e.g. publish of days inwards a week, states of water, publish of months inwards a calendar yr etc. After Generics, Enum is my minute favorite introduced inwards Java 5. Enum inwards Java is non similar its counterparts inwards C in addition to C++, where it but used to stand upwards for fixed publish of things, It is much to a greater extent than volatile tin dismiss produce lot to a greater extent than things which is non fifty-fifty possible inwards C or C++. Enum inwards Java is a Type similar whatsoever class or interface inwards Java. Enum likewise provides type-safety in addition to readability compare to pop Enum int pattern in addition to String enum pattern pop earlier Java 5.One of the pop utilisation of Enum is to create Thread-safe Singleton using Enum inwards Java. Enum tin override method inwards Java, Enum tin implement interface inwards Java. All Enum extends java.lang.Enum in addition to compile fourth dimension constant. See 10 Example of Enum inwards Java for to a greater extent than examples on how to utilisation Enum inwards Java.


    What is variable declaration method inwards Java
    As the cite advise variable declaration method are Java method which tin bring a variable publish of arguments e.g. y'all tin telephone telephone the method past times passing either 1 declaration or 2 arguments or fifty-fifty nix arguments. The mind method inwards Java five is retrofitted equally varargs method in addition to similar a shot its String[] declaration is converted to variable arguments. You tin implement varargs method fifty-fifty prior to Java five either past times using an anonymous array or using Collection classes e.g. List or Set. Variable declaration methods are likewise called equally varargs in addition to they are denoted past times 3 ...(dot) afterward in that place name. See What is varargs method inwards Java in addition to How to utilisation it for to a greater extent than details on variable arguments.

     varargs in addition to Enum along amongst several other features in addition to improvement Autoboxing, Enum, Generics, Varargs methods - Java five Features Quick Overview

    These were a quick overview of closed to of my favorite Java five feature. I create got included Autoboxing, Varargs, Enum, in addition to Generics exclusively but in that place are many to a greater extent than features inwards Java five which is worth looking e.g. static imports, regular appear in addition to Java Concurrency API which introduces closed to actually prissy utility similar CountDownLatch and CyclicBarrier, explore them to larn to a greater extent than nearly Java five advantages.

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

    Friday, November 8, 2019

    Java Enum Alongside Constructor Example

    Java Enum amongst Constructor
    Many Java developers don't know that Java Enum tin receive got a constructor to transcend information spell creating Enum constants. This characteristic allows you lot to associate related information together. One illustration of passing arguments to enum Constructor is our TrafficLight Enum where nosotros transcend activeness to each Enum illustration e.g. GREEN is associate amongst go, RED is associated amongst stop in addition to ORANGE is associated amongst the slow down. This is actually useful because it provides to a greater extent than context in addition to pregnant to your code. If you lot want, you lot tin likewise render 1 or to a greater extent than constructor to your Enum every bit it likewise supports constructor overloading like normal Java classes. This is real unlike from enum you lot receive got seen inward C or C++, which is only a collection of fixed affair without whatsoever OOP power.

    Just recall that constructor inward enums an exclusively endure either somebody or bundle marking it can't endure world or protected so access modifier public in addition to protected are non allowed to Enum constructor, it volition consequence inward compile fourth dimension error.

    By the way, this is non our offset tutorial on Java Enum where nosotros receive got explained a fundamental feature, nosotros receive got likewise ready covered approximately of import features on Enum inward our previous examples similar Java Enum Switch Example explains that you lot tin purpose enum constants within switch block.

    Similarly, Java Enum valueOf Example and Enum to String Example inward explains that how you lot tin acquire the String representation of Enum. These curt tutorials are a practiced agency to larn approximately useful features of enum inward Java.




    Java Enum amongst Constructor Example

    String declaration which is saved to activeness land which is afterwards accessed past times getter method getAction().

    As I explained, nosotros receive got an Enum TrafficSignal, which receive got iii enum constants, RET, GREEN, in addition to ORANGE, in addition to nosotros receive got associated, wait, croak in addition to tedious downward amongst them past times passing values into the constructor.
    t know that Java Enum tin receive got a constructor to transcend information spell creating Enum constants Java Enum With Constructor Example




    /**
     * Java enum amongst constructor for example.
     * Constructor bring 1 String declaration action
     */

    public enum TrafficSignal{
        //this volition telephone outcry upward enum constructor amongst 1 String argument
        RED("wait"), GREEN("go"), ORANGE("slow down");
     
        private String action;
     
        public String getAction(){
            return this.action;
        }
     
        // enum constructor - tin non endure world or protected
        TrafficSignal(String action){
            this.action = action;
        }
    }

    /**
     *
     * Java Enum illustration amongst constructor.
     * Java Enum tin receive got constructor but it tin not
     * endure world or protected
     *
     * @author http://java67.com
     */

    public class EnumConstructorExample{

        public static void main(String args[]) {
         
          //let's impress advert of each enum in addition to in that place action
          // - Enum values() examples

          TrafficSignal[] signals = TrafficSignal.values();
       
          for(TrafficSignal request : signals){
              //Java advert illustration - Java getter method example
              System.out.println("name : "
                                 + signal.name()
                                 + " action: "
                                 + signal.getAction());
          }
       
        }
     
    }


    This was our Java Enum illustration amongst Constructor. Now, you lot know that Enum tin have a constructor inward Java which tin endure used to transcend information to Enum constants, only similar nosotros passed activeness here. Though Enum constructor cannot endure protected or public, it tin either receive got somebody or default modifier only.


    Further Learning
    Complete Java Masterclass
    In-depth Guide of Enum inward Java
    10 Things Java Programmers Should Learn inward 2018
    How to croak a amend Java developer

    Thanks for reading this article so far. If you lot similar this curt tutorial in addition to so delight percentage amongst your friends in addition to colleagues. If you lot receive got whatsoever questions or feedback in addition to so delight drib a note.

    Saturday, November 23, 2019

    String To Enum Inwards Coffee - Conversion Example

    Creating Enum from String
    You tin practise Enum from String past times using Enum.valueOf() method. valueOf() is a static method which is added on every Enum degree during compile fourth dimension together with it's implicitly available to all Enum along alongside values(), name() together with cardinal() methods. In venture to practise Enum from String, String must live on same equally declared Enum otherwise, the code volition throw "java.lang.IllegalArgumentException: No enum const class". the same technique tin live on used to convert String into Enum instance equally well. This is the minute business office of Enum conversion tutorial, inwards the get-go part, nosotros accept seen how to convert Enum to String inwards Java. If you lot accept non read that yet, depository fiscal establishment check it out. Also from Java vii onwards, Java started supporting String constants inwards switch cases, merely you lot should ever prefer Enum over both Integer together with String constant because Enum provides type safety. The compiler volition ensure that wrong value is non supplied, merely inwards the instance of String together with Integer, the compiler volition depository fiscal establishment check whether a variable is of the right type, merely it won't depository fiscal establishment check values, which is why you lot should role Enum to define a well-known fixed give away of things. 



    Enum to String Conversion Example 

     is a static method which is added on every Enum degree during compile fourth dimension together with it String to Enum inwards Java - Conversion ExampleHere is a code illustration of String to Enum conversion inwards Java. It demonstrates both the technique which nosotros accept discussed thus far to practise Enum from String inwards Java. You tin role the same technique to convert whatever String to the corresponding Enum equally well. Always brand certain to overstep right String in venture to avoid IllegalArgumentExcpeiton in Java.



    There are few to a greater extent than or less other method of converting String to Enum also which compares passed String to all Enum instances declared past times iterating over all Enum instances using values() method together with and thus comparison them using equals(). Though that method industrial plant good it requires to a greater extent than code than unproblematic Enum.valueOf().

    Problem: We accept a declared Enum Currency, which contains Enum instances USD INR EURO, Now We accept a String "USD" together with nosotros desire to convert that String into Enum, it should convert into Currency.USD

    Solution: Currency.valueOf("USD") or Enum.valueOf(Currency.class, "USD")

    package example;

    /**
     * Java plan for creating Enum instance from String inwards Java.
     * This plan demonstrate how to role Enum.valueOf() method to convert enum instance
     * into String. beware that String must live on same equally declared Enum instances together with they are
     * instance sensitive equally well. "UsD" instead of "USD" volition throw IllegalArgumentException
     *
     * @author Javin Paul
     */

    public class StringToEnum {
        private enum Currency {USD, AUD, GBP, EURO }  
       
        public static void main(String args[]) {
           
            //Converting String to Enum inwards Java
            String usd = "USD";
           
            //Enum to String using Enum.valueOf()
            Enum currency = Enum.valueOf(Currency.class, usd);
           
            //Enum to String using Currency.valueOf()
            currency = Currency.valueOf(usd);
           
            System.out.println("String to Enum Example : " + currency);
         
            //This Enum to String conversion volition throw Exception
            String INR = "INR";
            //java.lang.IllegalArgumentException: No enum const degree
            Currency rupee = Currency.valueOf("INR");
        }
    }
    Output:
    String to Enum Example : USD
    Exception inwards thread "main" java.lang.IllegalArgumentException: No enum const class test.CollectionTest$Currency.INR
            at java.lang.Enum.valueOf(Enum.java:196)
            at test.CollectionTest$Currency.valueOf(CollectionTest.java:16)
            at test.CollectionTest.main(CollectionTest.java:32)
    Java Result: 1 


    That’s all on How to practise Enum from String inwards Java. This is a real frequent requirement  and Java programmers should live on familiar alongside this technique to convert String to Enum easily. In Summary prefer Enum over String to acquire compile fourth dimension checking together with type security merely since String is a global type together with you lot may shop your information inwards the database inwards the cast of String together with runtime each of those String converted to Enum.


    Further Learning
    Complete Java Masterclass
    see tip)
  • How to role valueOf method of Enum (check here)
  • String to Enum inwards Java alongside Example (check here)
  • Top xv Java Enum Interview Questions alongside Answers (see here)
  • Difference betwixt RegularEnumSet together with JumboEnumSet inwards Java (read here)
  • Learn how to role Enum inwards Java alongside a Simple Example (check here)
  • Can nosotros role Enum inwards Switch Statement inwards Java (Yes)
  • How to loop over Enum constants inwards Java (example)
  • What Every Java Programmer Should know close Enum (click here)
  • 10 points close Enum inwards Java (see here)
  • Can Enum accept Constructor inwards Java (learn here)
  • Wednesday, December 11, 2019

    How To Convert Bytebuffer To String Inward Java

    You tin easily convert ByteBuffer to String  in Java if you lot know how to convert byte array to String. Why? because it's really slowly to convert ByteBuffer to a byte array together with vice versa. All you lot take away to practise is telephone band the ByteBuffer.array() method, it volition render you lot the byte array used past times java.nio.ByteBuffer class, afterward you lot tin easily create String from that byte array. Though e'er recollect to render right grapheme encoding piece converting byte array to String. For example, if you lot know that ByteBuffer is filled amongst bytes encoded inwards UTF-8 hence you lot must utilisation the same encoding piece creating String from that byte array. String flat provides an overloaded constructor which accepts grapheme encoding along amongst byte array.  You tin utilisation the snippet shared inwards this representative to practise the job. ByteBuffer is i of the really useful flat inwards java.nio packet which is used to read information from channels together with write information into channel directly.

    Same ByteBuffer tin live on used to read together with write data. If you lot desire to read from ByteBuffer only telephone band the flip() method together with it volition convert ByteBuffer into reading mode. In this article, you lot volition larn how to convert ByteBuffer to String inwards Java. I guide maintain a given a unproblematic example, but if you lot nonetheless whatsoever dubiety you lot tin e'er move out a comment or question.


    ByteBuffer to String inwards Java - Example

    This is i of the simplest examples  to demonstrate how to convert ByteBuffer to String. In this Java program, I guide maintain outset created a String literal, hence I guide maintain got the byte array from that String inwards UTF-8 encoding scheme.



    After that, I guide maintain created a ByteBuffer object past times using same byte array together with using ByteBuffer.wrap() method. This is just the same province of affairs when your ByteBuffer is filled amongst information whether you lot read it from the network or a RandomAccessFile inwards Java. I guide maintain only used this direct approach to practise a ByteBuffer amongst information to simplify this example.

    Next piece of work of this plan is most of import because in that place nosotros are converting ByteBuffer to String. In companionship to acquire the byte array from ByteBuffer only telephone band the ByteBuffer.array() method. This method volition render the backed array.

     Now you lot tin telephone band the String constructor which accepts a byte array together with grapheme encoding to practise String. You are done.

    hither is our consummate code representative for converting ByteBuffer to String :


    import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer;   /**  * Java Program to convert ByteBuffer to String.  * It's slowly because its like to how you lot convert  * byte array to String.   *   * @author Javin Paul  */ public class HelloHP {      public static void main(String args[]) throws UnsupportedEncodingException {                 //Let's outset practise a ByteBuffer from String         String content = "It's slowly to convert ByteBuffer to String inwards Java";         ByteBuffer buffer = ByteBuffer.wrap(content.getBytes("UTF-8"));                 // Now let's convert this ByteBuffer to String         String converted = new String(buffer.array(), "UTF-8");                  System.out.println("Original : " + content);         System.out.println("Converted : " + converted);      }  }  Output : Original : It's slowly to convert ByteBuffer to String inwards Java Converted : It's slowly to convert ByteBuffer to String inwards Java

    That's all well-nigh how to convert ByteBuffer to String inwards Java. Just recollect to utilisation the right grapheme encoding because without using proper grapheme encoding in that place is no guarantee that you lot volition acquire master string back. Though UTF-8 is a proficient default it cannot live on used to render guaranteed.

    in Java if you lot know how to convert byte array to String How to convert ByteBuffer to String inwards Java

    Further Learning
    Data Structures together with Algorithms: Deep Dive Using Java
    tutorial)
  • How to convert Double to Long inwards Java? (tutorial)
  • How to convert Character to String inwards Java? (tutorial)
  • How to convert String to Int inwards Java? (example)
  • 5 Ways to convert Java 8 Stream to List? (solution)
  • How to convert SQL appointment to Util Date inwards Java? (example)
  • 5 examples of converting InputStream to String inwards Java? (tutorial)
  • How to convert Enum to String inwards Java? (guide)
  • How to convert a binary release to decimal in Java? (tutorial)
  • How to convert Array to Set together with List inwards Java? (example)
  • 3 examples of converting Array to ArrayList inwards Java (tutorial)
  • How to convert String to Enum inwards Java? (tutorial)
  • How to convert Hexadecimal numbers to octal together with binary inwards Java? (tutorial)
  • The best agency to convert Numbers to String inwards Java? (guide)
  • How to convert java.util.Date to java.sql.Date inwards Java? (tutorial)
  • How to convert ArrayList to Set inwards Java? (tutorial)
  • How to convert List to Set inwards Java? (example)
  • How to convert lowercase String to working capital missive of the alphabet inwards Java? (example)
  • 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.