Typesafe enum in JDK 1.5

Earlier version of the JDK did not have true enumerated types. Many developers have implemented workarounds for this, a popular one described in Effective Java, item 21. Starting from 1.5, enumerated types have been integrated with the language, allowing developers to write more robust programs without having to write dull boilerplate code, which is automatically generated.

A simple example showing some advantages of the new enum feature:

enum DestinationType
{
   queue,
   topic
}

public class Main
{
   public static void main(String []args) {
      DestinationType dt = DestinationType.queue;

      // Outputting an enumerated type is user-friendly
      System.out.println(dt);   // prints out "queue"
      
      // Switch can be used on an enumerated type, no need to qualify the name of the constant
      switch (dt) {
         case queue:  System.out.println("Using a queue");
                      break;
         case topic:  System.out.println("Using a topic");
                      break;
         default:
      }
   }
}

It is possible to iterate over all declared enum constants:

import java.util.*;

enum DestinationType
{
   queue,
   topic
}

public class Main
{
   public static void main(String []args) {
      printDestinations(DestinationType.values());
      
      // or
      
      for (DestinationType dt : DestinationType.values()) {
         System.out.println(dt);
      }
   }
   
   public static void printDestinations(DestinationType[] list) {
      for (int i=0; i<list.length; i++) {
         System.out.println(list[i]);
      }
   }
}

It is even possible to declare methods on enum constants and attach behavior to the constants.

DestinationType.java:

public abstract enum DestinationType
{
   queue {
      public void print(String queueName) {
         System.out.println("This is queue " + queueName);
      }
   },
   topic {
      public void print(String topicName) {
         System.out.println("This is topic " + topicName);
      }
   };
   
   abstract void print(String name);
}

Main.java:

public class Main
{
   public static void main(String []args) {
      DestinationType dt = DestinationType.queue;

      dt.print("queue1");
   }
}