Java Enum example

The enum type in java is a special data type that enables a variable to be set to one of a predefined set of values.

An enum can be in its own file (example: Directions.java) or included in an other class.

Example of a simple enum

enum Directions {
   NORTH, SOUTH, EAST, WEST 
}

A more elaborated example

enum Directions{
     NORTH("N"),
     SOUTH("S"),
     EAST("E"),
     WEST("W");
     // the ; after the fields is needed
     
     private final String symbol;
     
     Directions(String symbol){
      this.symbol=symbol;
     }
     
     public String symbol(){
      return this.symbol;
     }
}

 The use of an enum

Directions direction = Directions.EAST;

//...

switch(direction){
  case EAST:
   System.out.println("EAST");
   break;
  case SOUTH:
   System.out.println("SOUTH");
   break;
  case NORTH:
   System.out.println("NORTH");
   break;
  case WEST:
   System.out.println("WEST");
   break;
   
   default:
}

The above code will print the following:

EAST

 

You like this content ? Share it with you entourage !

Leave a Reply

Your email address will not be published.