enum type

An enumeration is created using the enum keyword.

For example, here is a simple enumeration:


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

The identifiers East, South are called enumeration constants. Enumeration constants is implicitly declared as a public, static final member of Direction.

The following program demonstrates the Direction enumeration:


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

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

The following code use enum with switch statement.


enum Coin {
  PENNY, NICKEL, DIME, QUARTER
}

public class Main {

  public static void main(String[] args) {
    Coin coin = Coin.NICKEL;
    switch (coin) {
    case PENNY:
      System.out.println("1 cent");
      break;
    case NICKEL:
      System.out.println("5 cents");
      break;
    case DIME:
      System.out.println("10 cents");
      break;
    case QUARTER:
      System.out.println("25 cents");
      break;
    default:
      assert false;
    }
  }
}
Home 
  Java Book 
    Language Basics  

enum:
  1. enum type
  2. values( ) and valueOf( ) Methods
  3. enum as Class
  4. enum type Inherit Enum
  5. Overriding toString() to return a Token constant's value
  6. Assign a different behavior to each constant.