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

YOU ARE READING
Java Programming
Acakhttps://docs.oracle.com/javase/tutorial/ This is the link where I learned my java lessons online. I choose java as first programming language. I am a career shifter. I just want to start something new. I choose to write it here in Wattpad so that I...