Java Enumeration Type

Introduction

An enumeration is created using the enum keyword.

For example, here is a simple enumeration that lists various directions:

// An enumeration of directions.  
enum Direction{  
   North, South, East, West
} 

Use the new defined enum type:

enum Direction{  
   North, South, East, West/*from   w  w  w.j  a v  a  2s .  com*/
} 
public class Main {  
  public static void main(String args[])  
  {  
    Direction ap = Direction.North;  
  
    // Output an enum value.  
    System.out.println("Value of ap: " + ap);  
    System.out.println();  
  
    ap = Direction.South;  
  
    // Compare two enum values.  
    if(ap == Direction.South)  
      System.out.println("ap contains South.\n");  
  
    // Use an enum to control a switch statement.  
    switch(ap) {  
      case North:  
        System.out.println("North.");  
        break;  
      case South:  
        System.out.println("South.");  
        break;  
      case East:  
        System.out.println("East.");  
        break;  
      case West:  
        System.out.println("West.");  
        break;   
    }  
  }  
} 

import java.util.Arrays;

public class Main {
   public enum FieldType {
      CSS, JAVA, HTML, SQL
   }//from   w w w. j av a  2 s . c  o m

   public static void main(String[] args) {

      FieldType field = FieldType.JAVA;

      System.out.println("field.name(): " + field.name());
      System.out.println("field.ordinal(): " + field.ordinal());
      System.out.println("field.toString(): " + field.toString());
      System.out.println("field.isEqual(JAVA): " + field.equals(FieldType.JAVA));
      System.out.println("field.isEqual(\"JAVA\"'): " + field.equals("JAVA"));

      System.out.println("field == JAVA: " + (field == FieldType.JAVA));
      // Won't compile - illustrates type safety of enum
      // System.out.println("field == \"JAVA\": " + (field ==
      // "JAVA"));

      System.out.println("field.compareTo(JAVA): " + field.compareTo(FieldType.JAVA));
      System.out.println("field.compareTo(CSS): " + field.compareTo(FieldType.CSS));

      System.out.println("field.valueOf(\"JAVA\"): " + field.valueOf("JAVA"));

      try {
         System.out.print("field.valueOf(\"JAVA\"): ");
         System.out.println(FieldType.valueOf("JAVA"));
      } catch (IllegalArgumentException e) {
         System.out.println(e.toString());
      }

      System.out.println("FieldType.values(): " + Arrays.toString(FieldType.values()));

   }
}



PreviousNext

Related