Java Enums

A Java Enum is a special Class that is used to defined a collection of constants. An Enum can contain constant, methods, etc. It was added in Java 5.

Enum Example

Consider a simple example to understand Enums in Java

public enum PlayerType {
     BATSMAN, 
     BOWLER, 
     ALLROUNDER, 
     WICKETKEEPER
}

Let’s consider you are working on a Application related to game of Cricket and you have to have a property for each player that defines his type (Batsman, Bowler etc). We have created a enum Class PlayerType which defines the constants that can be used for a Player.

Thus to refer any PlayerType your can do it by PlayerType.BATSMAN or PlayerType.WICKETKEEPER

This makes sure that Player are assigned the absolute value of constants and not any other random String type.

Enums in If-else Statements

Enums as Constants can be used in If-else statements. Consider the example below.

if(playerType == PlayerType.BATSMAN){
    System.out.println("Player is a Batsman");
}else if(playerType == PlayerType.ALLROUNDER){
    System.out.println("Player is an All Rounder");
}

Enums in Switch Statements

Enums can also be used in Switch statements, Let’s have a look into the below example

switch (playerType) {
    case BATSMAN: 
       System.out.println("Player is a batsman"); 
       break;
    case BOWLER: 
       System.out.println("Player is a bowler"); 
       break;
    case ALLROUNDER: 
       System.out.println("Player is all rounder"); 
       break;
    case WICKETKEEPER: 
       System.out.println("Player is wicketkeeper");
}

Iterating over Enum type

You can obtain all the values in Enum by Iterating over it through static values() method. Let’s look into the example below

for (PlayerType player : PlayerType.values()) {
    System.out.println(player);
}

The above code should print all the PlayerType Enum values

BATSMAN
BOWLER
ALLROUNDER
WICKETKEEPER

Enum Fields and Methods

You have an option to add fields to each Enum Type. Which is passed along in the constructor. To demonstrate this, Let’s consider that with the Enum PlayerType we decided to store each PlayerType Code as well. BATSMAN as 1, BOWLER as 2, ALLROUNDER as 3 and WICKETKEEPER as 4.

public enum PlayerType {
    BATSMAN(1), BOWLER(2), ALLROUNDER(3), WICKETKEEPER(4);

    int playerCode;

    PlayerType(int code) {
        this.playerCode = code;
    }

    public int getPlayerCode() {
        return playerCode;
    }

}

Notice that we have created a Constructor for our Enum Class which takes int code. In addition to that we have added an additional method as well getPlayerCode which demonstrates that Enum Type can also consist of methods.

Note: Java enums extend the java.lang.Enum class implicitly, so your enum types cannot extend another class.

tgugnani: Web Stuff Enthusiast.