Sunday, September 11, 2011

Java Enum Tutorial


In JDK 1.5 Enum was introduced. They are used to create multiple constants with a single given name. Enum constants are implicitly static and final and you can not change there value once created and they provides type-safety as well. Prior to JDK 1.5 we were using public static final constant to replicate enum like behavior. But this approach has some limitation. Lets take an example to understand it.

public class ServerStatus {
   public static final int STATUS_RUNNING = 0;
    public static final int STATUS_STARTED = 1;
    public static final int STATUS_CLOSED = 2;
    public static final int STATUS_FAILED = 3;
}

Limitations with this approach

1) Less Informative: Integer value shown to user e.g. 0 , 1 etc can not give full information unless user search what status does that int value represent.

2) No Meaningful Printing: Printing int value to show server status does not give meaningful information.

3) No Type-Safety: Since a server status is just an int you can pass in any other int value.

4) No Namespace: To access above constants we've to prefix class name e.g. ServerStatus.STATUS_RUNNING instead of using constant name alone.

All above limitations are fixed in JDK 1.5 with induction of Enum. Enum in Java is type-safe, provides meaningful string names and has there own namespace. Lets see how we can use Enum for same above given example.

public enum ServerStatus {
          STATUS_RUNNING,
            STATUS_STARTED,
            STATUS_CLOSED,
            STATUS_FAILED
}

Here ServerStatus is enum and STATUS_RUNNING, STATUS_STARTED, STATUS_CLOSED, STATUS_FAILED are enum constants. We followed similar naming convention for enum like class and interface (first letter in Caps) and since Enum constants are by default static final we have used all caps to specify them like Constants in Java.

Advantage of using Enum in Java

1) Enum is type-safe. You can not assign any value other than predefined enum constant.

2) Enum has its own name-space.

3) Adding new constants in Enum in Java is easy.

4) You can define constructor, methods and variables inside java enum. Constructor of enum in java must be private otherwise it gives compilation error.

5) We can specify values of enum constants at the creation time as shown below:

public enum ServerStatus {
          STATUS_RUNNING(0),
            STATUS_STARTED(1),
            STATUS_CLOSED(2),
            STATUS_FAILED(3)
}

But to do this , it is prerequisite to define a member variable and a constructor because STATUS_STARTED(1) is actually calling a constructor which accepts int value.

6) Enum constants are implicitly static and final and can not be changed once created.
     For Ex: ServerStatus.STATUS_RUNNING = ServerStatus.STATUS_STARTED; 
    will give compilation error.

7) Instance of Enum can not be created because constructor defined in Enum is private.

8) Iteration of Enum constants is also possible. Values() method returns array of enum constants and can be iterated as shown below:

for(ServerStatus status: ServerStatus.values()){
        System.out.println("status: " + status);
}

9) Enum constants can be compared using "==" equality operator.

10) Enum constants in java can be used as an argument in Switch statement.

 ServerStatus status = ServerStatus.STATUS_RUNNING;
    switch (status) {
            case STATUS_RUNNING:
                    System.out.println("Running");
                    break;
            case STATUS_STARTED:
                    System.out.println("Started");
                    break;
            case STATUS_CLOSED:
                    System.out.println("Closed");
                    break;
            case STATUS_FAILED:
                    System.out.println("Failed");
    }

That's all for enums, you are all set to play around with Enums.


1 Responses to “Java Enum Tutorial”

Javin Paul said...
December 21, 2011 at 9:27 PM

Enum also provides some inbuilt useful methods like name(), orndinal(), values() and valueOf() which can be used to convert String to Enum in Java , get the order of Enum as it is declared in Class and get all the values of Enum. I agree Enum is very versatile , you can check 10 Example of Enum in Java to see how Enum can be used in lot of different way.


Post a Comment

© 2011 a2ztechguide.com • All rights reserved.
Blogger Template by Bloggermint