Java Enum type
In this chapter you will learn:
- What is Java Enum
- How to create enum type in Java
- Define enum type variable
- Compare two enum values
- 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:
- How to use use values() and valueOf() from enum
- Syntax for Enum values() and valueOf() Methods
- Example - Enum values() and valueOf() Methods