Showing posts with label enum. Show all posts
Showing posts with label enum. Show all posts

Sunday, 6 November 2016

Enum constant should be the first field in the enum

Java requires that the constants be defined first, prior to any fields or methods. Also, when there are fields and methods, the list of enum constants must end with a semicolon.

enum constants with compilation error:
public enum DayEnum {
    
     String value;
     /*Multiple markers at this line
     - Syntax error on token "String", invalid Modifiers
     - Syntax error on token ";", , expected*/
    
     SUNDAY, MONDAY, TUESDAY, WEDNESDAY,THURSDAY, FRIDAY, SATURDAY;
}

enum constants as first statement without any compilation error:
public enum DayEnum {
    
     SUNDAY, MONDAY, TUESDAY, WEDNESDAY,THURSDAY, FRIDAY, SATURDAY;
    
     String value;
}

Tuesday, 3 November 2015

Java.lang.Enum.ordinal() Method

Java.lang.Enum.ordinal() Method

The ordinal() method returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero).

public final int ordinal()



public class EnumOrdinal {

     // enum showing Laptop prices
     enum Laptop {
           Dell(1600), HP(1500), Lenovo(1000);

           int price;
           Laptop(int p) {
                price = p;
           }
           int showPrice() {
                return price;
           }
     }

     public static void main(String args[]) {

           System.out.println("Laptops :");

           for(Laptop lap : Laptop.values()) {
                System.out.println("Ordinal value of "+lap.name()+
                           " is "+lap.ordinal());
           }
           System.out.println("HP index "+ Laptop.HP.ordinal());
     }
}

Output:
     Laptops :
     Ordinal value of Dell is 0
     Ordinal value of HP is 1
     Ordinal value of Lenovo is 2
     HP index 1

Monday, 26 October 2015

Can be declare enum inside the interface?

It's perfectly legal to have an enum declared inside an interface.

In this situation the interface is just used as a namespace for the enum and nothing more. The interface is used normally wherever we use it.


public interface IService {
     public enum Status { // enum
           OK(200), INTERNAL_ERROR(500), KO(0);

           private int errorCode;

           private Status(int errorCode) {
                this.errorCode = errorCode;
           }

           public int getErrorCode(){
                return errorCode;
           }
     }
}

Friday, 9 October 2015

Java Enums are Inherently Comparable


enums are automatically Comparable, there is no need to explicitly add the "implements Comparable".

When we check the enum weather it is instance of Comparable, it return true.


enum Day {
       SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
       THURSDAY, FRIDAY, SATURDAY;
}

public class EnumTest {
       public static void main(String[] args) {
              Day day = Day.MONDAY;
              String isComparable = "Not Comparable";

              if(day instanceof Comparable) {
                     isComparable = "Comparable";
              }

              System.out.println(isComparable);
       }
}
Output: Comparable



Serialization of Enum Constants

Enum constants are serialized differently than ordinary serializable or externalizable objects. The serialized form of an enum constant consists solely of its name; field values of the constant are not present in the form.

To serialize an enum constant, ObjectOutputStream writes the value returned by the enum constant's name method.

To deserialize an enum constant, ObjectInputStream reads the constant name from the stream; the deserialized constant is then obtained by calling the java.lang.Enum.valueOf method, passing the constant's enum type along with the received constant name as arguments.

Important points:


enum constants are serialization cannot be customized with writeObject, readObject, readObjectNoData, writeReplace, and readResolve methods, enum types are ignored during serialization and deserialization by these methods.

All enum types have a fixed serialVersionUID of 0L.


Java Enums are Inherently Serializable


enums are automatically Serializable, there is no need to explicitly add the "implements Serializable".


import java.io.Serializable;

enum Day {
      SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
      THURSDAY, FRIDAY, SATURDAY;
}

public class EnumTest {
      public static void main(String[] args) {
            Day day = Day.MONDAY;
            String isSerializable = "Not Serializable";

            if(day instanceof Serializable) {
                  isSerializable = "Serializable";
            }
           
            System.out.println(isSerializable);
      }
}

Output: Serializable

Important points about Enum in Java

1. Enum is type-safe and has its own name-space.
We cannot assign any value other than specified in Enum Constants to Currency variable coin.


public enum Currency {PENNY, NICKLE, DIME, QUARTER};
Currency coin = Currency.PENNY;
coin = 1; //compilation error


2. Enum is reference type like class or interface and you can define constructor, methods and variables inside java Enum which makes it more powerful than Enum in C and C++.

3. Values of enum constants can specify at the creation time:

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

However for to specify the values, we need to define a member variable and a constructor because PENNY (1) is calling a constructor which accepts int value.


public enum Currency {
    PENNY(“1”), NICKLE(“5”), DIME(“10”), QUARTER(“25”);
    private String num;

    private Currency(String num) {
            this.num = num;
    }
};


4. Constructor of enum must be private any other access modifier will result in compilation error.

5. We can define methods in enum. To get the value associated with each coin, define a public getValue() method.


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

      private String value;
      private Currency(String brand) {
            this.value = brand;
      }
     
      public String getCurrValue() {
            return value;
      }
}


6. Enum constants are implicitly static and final and cannot be changed once created.


// The final field EnumTest.Currency.PENNY cannot be assigned
Currency.PENNY = Currency.NICKLE;


7. Enum can be used as an argument on switch statement and with "case:" like int or char primitive type.


Currency currency = Currency.PENNY;
switch (currency) {
case PENNY:
      System.out.println("coin # "+Currency.PENNY);
      break;
case NICKLE:
      System.out.println("coin # "+Currency.NICKLE);
      break;
case DIME:
      System.out.println("coin # "+Currency.DIME);
      break;
case QUARTER:
      System.out.println("coin # "+Currency.QUARTER);
}


8. Since constants defined inside Enum in Java are final you can safely compare them using "==" equality operator.


Currency num = Currency.PENNY;
if(num == Currency.PENNY){
      System.out.println("ENUM compared using equal method !");
}


By the way comparing objects using == operator is not recommended, Always use equals() method or compareTo() method to compare Objects.

9. Java compiler automatically generates static values() method for every enum which returns array of Enum constants in the same order they have listed in enum.


/** It will print all the value of the ENUM. */
for(Currency c : Currency.values()) {
      System.out.println(" # "+ c);
}


10. We can override methods in enum.
Overriding toString() method inside enum to provide meaningful description for enums constants.

11. Two new collection classes EnumMap and EnumSet are added into collection package to support Java Enum.
These classes are high performance implementation of Map and Set interface.

12. private constructor of Enum is not allowed to create instance of enums by using new keyword. Enums constants can only be created inside Enums itself.

13. Instance of Enum is created when any Enum constants are first called or referenced in code (loading the enum in JVM).

14. Enum can implement the interface and override any method like normal class. It’s also worth noting that Enum in java implicitly implement both Serializable and Comparable interface.


public enum Currency implements Runnable {
      PENNY(“1”), NICKLE(“5”), DIME(“10”), QUARTER(“25”);
      private int num;
      ............

      @Override
      public void run() {
            System.out.println("Enum in Java implement interfaces");

      }
}


15. We can define abstract methods inside enum and can provide different implementation for different instances of enum.



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 "gold";
            }
      };


      /**
       * ENUM constructor is always private
       * Cannot make object of ENUM using new keyword because
       * of private constructor.
       */
      private Currency(String currency ) {
            this.currency = currency;
      }

      private String currency;

      @Override
      public String toString() {
            return this.name()+" : "+this.getCurrency();
      }

      /** abstract method in ENUM.
       * Need to implement in all ENUM. */
      public abstract String color();

      public String getCurrency() {
            return currency;
      }
}

public class EnumTest {
      public static void main(String[] args) {
            Currency currency = Currency.PENNY;
            System.out.println(currency+", color: "+currency.color());
      }
}
Output: PENNY : 1, color: copper
Related Posts Plugin for WordPress, Blogger...