How to create enum type in Java

Description

An enumeration is a list of named constants.

Syntax

An enumeration is created using the enum keyword.

For example, here is a simple 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.

Enum type variable

Once you have defined an enumeration, you can create a variable of that type.

Even though enumerations define a class type, you do not instantiate an enum using new.

The following code declares ap as a variable of enumeration type Direction:


Direction ap; 

Because ap is of type Direction, the only values that it can be assigned are those defined by the enumeration. For example, this assigns ap the value South:


ap = Direction.South; 

Compare

Two enumeration constants can be compared for equality by using the == relational operator.


// An enumeration of direction varieties. 
enum Direction {
  East, South, West, North// w w w .j  av a2s  . c  o m
}

public class Main {
  public static void main(String args[]) {
    Direction dir = Direction.South;

    System.out.println("Value of dir: " + dir);

    dir = Direction.South;

    if (dir == Direction.South){
      System.out.println("ap contains GoldenDel.\n");
    }
  }
}

The code above generates the following result.

Enum Switch

An enumeration value can also be used to control a switch statement.


enum Direction {/* ww w.jav a2  s.com*/
  East, South, West, North
}

public class Main {
  public static void main(String args[]) {
    Direction dir = Direction.South;
    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 code above generates the following result.





















Home »
  Java Tutorial »
    Java Data Type »




Java Boolean
Java Byte
Java Character
Java Currency
Java Double
Java Enum
Java Float
Java Integer
Java Long
Java Short
Java Auto Grow Array
Java Array Compare
Java Array Convert
Java Array Copy Clone
Java Array Fill
Java Array Search and Sort
Java String Convert
Java String File
Java String Format
Java String Operation
Java BigDecimal
Java BigInteger