Java Enum (Enumerations)

It is basically a data type.

public enum Temperature {
    HIGH,
    MEDIUM,
    LOW
}

You can use enum types any time you need to represent a fixed set of constants.

For loop

enum Directions {
    NORTH, SOUTH, EAST, WEST
}
public class LoopEnum
{
    public static void main(String[] args)
    {
        int cnt = 1;
        // loop through enum
        for (Directions dir: Directions.values())
        {
            System.out.printf("Direction -> %d = %s\n", cnt++, dir);
        }
    }
}

Pros:

Set of Constant declaration

Restrict input parameter in method

Can be usable in switch-case

Type safety and value safety

results matching ""

    No results matching ""