Java Enum type

In this chapter you will learn:

  1. What is Java Enum
  2. How to create enum type in Java
  3. Define enum type variable
  4. Compare two enum values
  5. An enumeration value can also be used to control a switch statement

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 ww.  j a  v a  2 s .  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 {/* www.  j  a va  2  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.

Next chapter...

What you will learn in the next chapter:

  1. How to use use values() and valueOf() from enum
  2. Syntax for Enum values() and valueOf() Methods
  3. Example - Enum values() and valueOf() Methods
Home »
  Java Tutorial »
    Java Langauge »
      Java Enum
Java Enum type
Java Enum values() / valueOf() Methods
Java Enum as Class
Java Enum Inherit Enum
Java Enum compareTo
Java Enum equals
Java Enum Behaviour