Defining a Fixed Set of Related Constants - Java Language Basics

Java examples for Language Basics:enum

Introduction

Use an enum type.

Demo Code

import java.util.Arrays;

enum Direction {/*from ww w .  j  av a  2 s  .  c  om*/
  East, WEST, NORTH, SOUTH
}
public class Main {
    public static void main(String[] args) {
        Direction field = Direction.WEST;

        System.out.println("field.name(): " + field.name());
        System.out.println("field.ordinal(): " + field.ordinal());
        System.out.println("field.toString(): " + field.toString());
        System.out.println("field.isEqual(WEST): " + field.equals(Direction.WEST));
        System.out.println("field.isEqual(\"WEST\"'): " + field.equals("WEST"));

        System.out.println("field == WEST: " + (field == Direction.WEST));


        System.out.println("field.compareTo(WEST): " + field.compareTo(Direction.WEST));
        System.out.println("field.compareTo(PASSWORD): " + field.compareTo(Direction.East));

        System.out.println("field.valueOf(\"WEST\"): " + field.valueOf("WEST"));

        System.out.println("FieldType.values(): " + Arrays.toString(Direction.values()));

    }
}

Result


Related Tutorials