Enum

5 0 0
                                        

Enum is used when you want to create a set of constant values like the Days of the Week and so on.

Syntax: 

    enum EnumName {

        // whatever constants you want to defined in here

    }

======================

public class EnumTypesDemo {
enum TrafficLights {
RED, GREEN, YELLOW
}

void display(TrafficLights lights){
switch (lights){
case RED -> System.out.println("STOP");
case GREEN -> System.out.println("GO");
case YELLOW -> System.out.println("READY");
default -> System.out.println("Obey the traffic lights!");
}
}
public static void main(String[] args){
EnumTypesDemo demo = new EnumTypesDemo();
demo.display(TrafficLights.GREEN);
}
}

======================

Result:

GO

When you invoke or call an Enum, just used the name followed by the dot operator and the constant value.

Note: 

    1. Java prepares a set of methods that is ready to be used when create an enum.

    2. Enum constant can have values.

    3. Enum is like a class but with an Enum type only. So, it can have properties and methods inside as well.

=======================

public class EnumTypesDemo {
enum TrafficLights {
RED("STOP"), GREEN("GO"), YELLOW("READY");
private final String trafficValue;
TrafficLights(String trafficValue){
this.trafficValue = trafficValue;
}

String getTrafficValue(){
return trafficValue;
}

}
void display(TrafficLights trafficLights){
System.out.println(trafficLights.getTrafficValue());
}
public static void main(String[] args){
EnumTypesDemo demo = new EnumTypesDemo();
for(TrafficLights tl: TrafficLights.values()){
demo.display(tl);
}

}
}

=======================

Result:

STOPGOREADY

Java ProgrammingWhere stories live. Discover now