1. "Hello, World!"
  2. Variables and Types
  3. Arrays
  4. While, If, For
  5. ...Problem Set 0
  6. Static Methods
  7. Static Fields
  8. String Conversion
  9. Objects
  10. Threading
  11. Strings
  12. ...Problem Set 1.5
  13. Packages
  14. Complex Numbers
  15. Abstract classes
  16. Interfaces
  17. Autoboxing
  18. ...Problem Set 1
  19. enum
  20. Inner Classes
  21. Polymorphism
  22. Tanks!
  23. Callbacks
  24. Exceptions
  25. File I/O
  26. ...Problem Set 2
  27. Regular Expressions

enum

An enum is a language construct that allows you to create a type with a finite list of possible values, kind of like choosing from a menu.

Direction.java
1public enum Direction {
2    NORTHSOUTHEASTWEST
3}
$ javac Direction.java

The next example shows you how you can use enums. They are types that can be compared with == or !=. They have string representations that are the same as their declared name.

UseDirection.java
1public class UseDirection {
2    public static void main(String[] args) {
3        Direction d1 = Direction.EAST;
4        Direction d2 = Direction.SOUTH;
5        if(d1 == d2)
6            System.out.println("equal!");
7        else
8            System.out.println(d1+" is not equal to "+d2);
9    }
10}
$ javac UseDirection.java
$ java UseDirection
EAST is not equal to SOUTH

If you want to store additional information in an enum, you can.

ExDirection.java
1public enum ExDirection {
2    // provide values with constructors, put semicolon at the end
3    NORTH(1,0)SOUTH(-1,0)EAST(0,1)WEST(0,-1);
4 
5    // define fields
6    public final int deltaX,deltaY;
7 
8    // define constructors
9    ExDirection(int dx,int dy) {
10        deltaX = dx;
11        deltaY = dy;
12    }
13}
$ javac ExDirection.java