Enum in java with java enum examples

Enum in java



This tutorial consists of introduction to enum in java, java enum example (s), need of enum class in java with enum example. Enum in java or enums in java introduced in J2SE 5 , but what is enum in java? when to use enum in java, how to use enum in java , how to declare enum in java? how to serialize enum in java? how to sort enum in java? how to use java enum constructor ? there are lots of questions isn’t it? Lets look at how we can use enum in java. Enum in java are nothing but set of fields with set of fixed constants.
Before enum introduced in java , there were constants defined in the class as follows :
public Class ConstantPool{
     public static final int TCP_PORT = 123;
     public static final int DNS_PORT = 139;
     public static final int LDAP_PORT = 922;
} 

In above java example we can see that we need to specify the constants using public static final int. These constant replicate enum like behaviour. But above program looks and easy and okay for a requirement, you must be wondering why we need to use enum in java. There is an answer to it and it is indeed need to be understood.
The approach of defining set of constant values are some serious drawbacks, lets see which are those and enum in java comes for help.
1. Missing type-safety :
First and foremost it is not type-safe. You are allowed to assign any port value which is not actual port value. Thus these constant can allow illegal values.
2. Missing Significant printing
Significant printing of the constant is missing from the way of defining constants using static final scheme. Like when we print the constant it will print the value such as 123 not TCP_PORT.
3. I/O on final static Strings not easy.
For converting values from String to I/O operations is not easy.
4. No behaviour of its own
Constant Strings defined by static and final are only values there is no behaviour associated with it.


Enum in java or enums in java helps in overcoming these limitations.

Enum in Java



Now lets see what is enum in java and how it helps in improving programming. Enum is like a class or an interface which keeps fixed set of constants, which we call as enum constants. Lets see how we can define the Enum constants :

// Java enum example 1.
public  enum  Ports{ 
 TCP,
               DNS,
 LDAP
}; 

In above code snippet we can see that out enum is PORTS and TCP, DNS , LDAP are the constants.
Now if we closely look at the code snippet above we can see that curly braces are like classes and interfaces. Also enum word is used like class or an interface. Naming convention is like a Class and and inter face too.
Enum constants are implicitly static and final. That means you cannot change the constant value again.
Another thing to watch for is if you were using java 1.4 and you have used enum as variable name , it will fail in case of java 1.5.

Now lets see benefits of using enum in java :

1. Unlike using array of Strings , we can use enums as case labels.
2. Enum in java are type safe.
3. If you are using lower version than java 7, then you can use enum in Switch statement.
4. We can easily add additional fields to the enum in java.
5. Enum in java uses its own namespace.
6. We can compare enums easily with ==.
7. Enum in java helps in reducing the bugs in our code. Lets see how if you have different ports but you want to restrict some of the ports such as reserved ports. So when you make constants using enum in java, compiler will restrict you from assigning the different ports other than TCP, DNS and LDAP.

[tip]
Enum in java are typesafe.

Enum in java uses its own namespace.

[/tip]
Declaration of enum in java :
Enums can be declared as their own separate class or as a class member. First we will see declaring enum in java outside a class :

// Java enum example 2. Declaration of enum in java
enum Ports {  TCP, DNS, LDAP  } // Declaring enum outside the class.
class PortSpec {
 Ports ports;
} 
public class testPortSpec {
 public static void main( String[] args ){
  PortSpec portSpec = new PortSpec();
  portSpec.port = Ports.TCP; // Using enum which is outside the class.
}
}

In above code we can see that we have declared enum outside the class , but we can see that enum need to be declared with only the public or default modifier like non-inner class.
[tip]
Enum in java need to be declared with only the public or default modifier.
[/tip]

Java Enum Example 3 : Declaring enum inside the class
class PortSpec {
 enum Ports {  TCP, DNS, LDAP  } // Declaring enum inside the class.
 Ports ports;
} 
public class testPortSpec {
 public static void main( String[] args ){
  PortSpec portSpec = new PortSpec();
  portSpec.port = PortSpec. Ports.TCP; // Using enum which is inside the class PortSpec.
}
}

In above code snippet we have seen that we can use enums inside the class. But syntax for accessing an enum’s members depends on where the enum is delared.
[tip]
Enum constant must not be declared inside a method .
[/tip]
Java Enum Example 4 : Declaring enum inside the class is wrong.
public class testPortSpec {
 public static void main( String[] args ){
  enum Ports {  TCP, DNS, LDAP  } // Wrong !
PortSpec portSpec = new PortSpec();
  portSpec.port = Ports.TCP; // 
}
}

Above code we can see that we cannot declare the enum constant inside the method.
Convention for enum in java :
Common convention is enum constant to be in all UPPERCASE.
So far we seen how to declare the enum constants, but you must be curious to know what gets created when we make an enum in java. In above code snippet as we can see each of the enum declared in Ports is actually instances of Class Ports i.e. TCP is type of Ports like
public static final Ports TCP = new Ports( “TCP”, 123 );
Here you can see that it has been declared as static and final which we assume it is a constant.
Now lets see some of the key features of enum in java .
1. Declaring a constructor in enum in java
We can specify value to the enum constant at the time of creation. We can create the constructor to specify the value as shown below :
Java Enum Example 5 : Constructor of enum in java is declared as private
public class Ports{
TCP(123), UDP(345), LDAP(555);
public int portNumber;
private Ports( int portNumber ){  //Access modifier private  
 this.portNumber = portNumber;
}
};

In above code, we can see the Constructor of enum in java is declared as private, it must always be private, because any other access modifier can throw compile time error.
[tip]
Java enum constructor :

Constructor of enum in java should be declared as private.
[/tip]

Also to get the value associated with constant we can add getValue() method which will give
the value associated with it.


2 As we seen above, as constructor is private, we cannot create instance of enum using new operator. So Enum constants can only be created in Enum class itself. The enum constructor is invoked automatically, with the arguments you define after the constant value.
You can also pass more than one argument to the enum constructor in java, similarly overloading of enum constructor is also possible.


3.All enums and enum constant have some built in or predefined methods such as values() and valueOf()

1. Public static EnumType[] values()
This method returns the array of enumeration constants.
2. Public static EnumType valueOf( String str )
This method return enum constant which corresponds to the String passed as an argument.

Java Enum Example 6 : Example of values() method in enum in java.
Ports allPorts[] = Port.values(); // Returns array of enum constants.
For( Ports portNumber : allPorts ){
 System.out.println(  portNumber );
}


Java Enum Example 7 : valueOf( String str ) example of enum in java..
Ports port = Port.valueOf(“TCP”); // Returns enum constant for  TCP

But what happens when we pass empty value to the valueOf function ? Guess! Right, it throws IllegalArgumentException in enum in java.
Also enum values are case sensitive so make sure you pass correct case parameter with doing trom() to valueOf function.

5.

Ordinal in enum in java

:
Ordinal in enum in java means the position in enum declaration. We don’t need to assign ordinals manually. These ordinals are self numbered. Ordinal values can be found out by using ordinal() method.

Java Enum Example 8 : Java enum ordinal example
 
for( Ports portNumber : allPorts ) {
 System.out.println(  portNumber.ordinal()  );
 }

If we want to get enum constant from the ordinal you can do it as follows :


Java Enum Example 9 : How to get enum constant from the ordinal in enum in java.
Port portNo = Port.values()[ ordinal ];


6. Constants defined inside enum in java are static and final so we can directly compare them using == operator.
Following program demonstrates the use of equality operator in enum in java.
Port tcpPort = Port.TCP;
If(  tcpPort == Port.TCP  ){
 System.out.println(  “Ports are equal” );
}


8.Enum in Switch statement :
Enum in java can be used as an argument to the Switch statement to be used as a case as we use it in case of int and char type. Before Java 7 we were not using String in Switch case statement. (Java 7 uses String in Switch statement) but for some reason if you are not using java 7 and above then enum makes a great option to be used in Switch statement.
Java Enum Example 9 : java enum switch example
Port portNumber = Port.TCP;
switch( portNumber ){
 case TCP:
  System.out.println(  “TCP Port Found” );
 case LDAP:
  System.out.println(  “LDAP Port Found” );
} 

9.Sorting enum in java

Sorting of enums can be done in same way as we do in sorting of array in java. You can create the Comparator object and use it to sort the enum constants in java.

Java Enum Example 10 : Sorting of enum in java


//Using util classes to sort enums
import java.util.Arrays;
import java.util.Comparator;

import static java.lang.System.out;

/**
 * This is an example of sorting or array of enums.
 *
 */
public class EnumSortExample
    {
    public static void main( String[] args )
        {
        Ports[] portNames = { Ports.TCP, Ports.DNS, Ports.LDAP };
        Arrays.sort( portNames ); // default sort
        for ( Ports portInfo : portNames )
            {
                System.out.println( portInfo + " " + portInfo.getPortUidName() +" "+portInfo.ordinal() );
            }
        // Default sorting is done according to the ordinal
        //TCP Tcp 0
        //DNS Dns 1
        //LDAP Ad 2
        Arrays.sort( portNames, new PortUidOrder() ); // sort by port uid
        for ( Ports portInfo : portNames )
            {
                System.out.println( portInfo + " " + portInfo.getPortUidName() +" "+portInfo.ordinal() );
            }
        // displays in Latin name order
        //LDAP Ad 2
        //DNS Dns 1
        //TCP Tcp 0
        }
    }

/**
 * Enum for Ports
 */
enum Ports  // 
    {
        TCP( "Tcp" ),
        DNS( "Dns" ),
        LDAP( "Ad" );

    final String portUidName; //Field name for storing port Uid name

    
    Ports( String uidName ) // Constructor
        {
        this.portUidName = uidName;
        }

    // GET / SET METHODS 

    String getPortUidName()
        {
        return portUidName;
        }
    }

/**
 *Creating Comparator class to sort enum by port uid
 */
class PortUidOrder implements Comparator
    {
    // Compare function to compare enums
    public final int compare( Ports a, Ports b )
        {
        return a.portUidName.compareToIgnoreCase( b.portUidName ); // Comparing the enums using compareToIgnoreCase
        }
    }


Serialization of java enum


Serialization of java enum means converting java enum to a value which can be either primitive or String to store it easily either in database or file or disk. Deserialization is the process where stored value read back and converted to enum.
Lets see how enum in Java can be serialized :
1. Using user defined value ( Most recommended )
In this approach of serialization and de- serialization user defines one custom value to each enum constant and use toValue() and fromValue() functions to get the constant back. This approach is more dependable as it do not depend upon the ordering of the enum constant or the enum constant itself.
//Following code snippet shows use of toValue() and fromValue() functions 
public enum Ports {
 TCP("TCP"), DNS("DNS"), LDAP("AD"), UNKNOWN("UNKNOWN");

 private final String value;

 Ports( String value ) {
   this.value = value;
 }
// Usiing fromValue method to get the actual port
 public static Ports fromValue(String value ) {
   if ( value != null ) {
     for ( Ports port : values() ) {
       if (port.value.equals( value )) {
         return port;
       }
     }
   }
//here you can either return default or throw illegal argument exception
 }
 public String toValue() {
   return value;
 }
}


Serialization of enum in java
Ports port = Ports.TCP;
String savedPort = port.value(); //Serialization done using value()

De-serialization of enum in java
 
 Ports savedPortEnum = Ports.fromValue( savedPort );

2. Using name() value :
We can use name() method to get the enum constant value. Lets see how we are serializing the enum constant using this approach :

Ports port = Ports.TCP;
String savedPort = port.name();

De-serialization of enum in java :
Port savedPortEnum = Ports.valueOf( savedPort );
 


Overriding toString in enum in java


Sometimes we need custom values for enum constants. To achive this we can use or override toString method. Overriding should be done only when we need more programmer friendly String to be used.

Enum implementing an interface :

1.Enum in java implicitly implements Comparable and Serializable interfaces.
2. But why would an enum implement an interface?
Enum in java don’t just provide set of passive constants. They may also have a complex functionality or behaviour.
3. How to implement interface using enum in java?
Lets see how we can implement an interface using java enum.
        public enum Ports implements Connectable(){
  TCP(123), UDP(345), LDAP(555);


 public void connect(){
 ......
}
}

Thus we see in above article some important aspects of enum in java using java enum example (s). Like declaring enum constant in java, built in functions such as values() and valueof(), ordinal in enum, sorting java enums, serialization of java enum. Hope you liked this article about enum in java.
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

6 comments:

  1. Very good set of examples on Java enums

    ReplyDelete
  2. Greate article, nice one with examples.

    ReplyDelete
  3. this is suberb Example i ill realy recommend to every one

    ReplyDelete
  4. hey very nice examples.

    but still i have one question how to user enums in thread communication.
    actully i m doing a project in android in which i am using multiple threads and for communication between the threads i m using messages which are nothing but enums so now my questions is how to pass enums between the threads.

    ReplyDelete
  5. nice explanation ..

    ReplyDelete
  6. excellent transformation and explanation

    ReplyDelete