Enumeration in Java

Rmag Breaking News

In this article, we will discuss about the Enums in Java but even before we go into enums let’s understand why do we need it?

When we build a Java Application we may define variables which remain constant forever. For eg. Months or a year, name of seasons, etc.These variables can be defined as Enum.

Enum is basically a language construct and one can use this variable to define type safe variables.

Enum may contains one or more enum constants.

This is how the enum can be defined:

Public enum Day{
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

Let’s take one more example here

enum Color{
RED(“red”), GREEN(“green”), BLUE(“blue”);

private String value;

Color(String value){
this.value = value;
}

public String getValue(){
return value;
}
}

Here in this second example the name of the enum type is constant but it will have an internal value so here RED is what the consumer will see and use but “red” is the one that will be used inside your application (It is just for simplicity, useful when you have something lengthy like WHO(“World Health Organization”)).

Extra code written here to fetch the value of this Enum. Like whenever any consumer want to get the value here , getValue() can be used.

Now let’s see how can we use this enum in the program.

public class Main{
public static void main(String[] args){
Color c1 = Color.GREEN;
System.out.println(“GREEN Enum value: “+c1.getValue());
}

Output: green

Thank you and happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *