Part 12: Enums in java with uses example code.

Part 12: Enums in java with uses example code.

Enums in java

An enum is a group of constants. To create an enum, use the enum keyword instead of class or interface. Also separate the constants with a comma. It is use when you have values that you know aren’t going to change such as month days, days, colors, deck of cards, etc. They should be in uppercase letters:

Example
enum Days {
SAT,
SUN,
MON,
TUE,
WED,
THU,
FRI
}

You can access enum constants with the dot syntax:

Days myVar = Days.MON;
Enum is short for “enumerations”, which means “specifically listed”. Enum inside a Class example:

Example

public class Month

{
enum Level

{
SAT,
SUN,
MON,
TUE,
WED,
THU,
FRI
}

public static void main(String[] args)

{
Days myVar = Days.MON;
System.out.println(myVar);
}
}

The output will be:

MON

Enums in a Switch Statement:

Enums are often used in switch statements to check for corresponding values:

Example
enum Level

{
SAT,
SUN,
MON,
TUE,
WED,
THU,
FRI
}

public class Main {
public static void main(String[] args) {
Days myVar = Days.MON;

switch(myVar) {
case SAT:
System.out.println("This is Saturday");
break;
case MON:
System.out.println("This is Monday");
break;
case SUN:
System.out.println("This is Sunday");
break;
}
}
}

 

The output will be:

This is Monday

Loop Through an Enum:

The enums type has a values() method where they returns an array of all enums constants. This method is useful when you want to loop through the constants of an enums:

Example
for (Days myVar : Days.values()) {
System.out.println(myVar);
}
The output will be:

SAT
SUN
MON

Difference between Enums and Classes

An enums is like a class which have attributes and methods. The only difference is that enum constants are public, static and final that is unchangeable also cannot be overridden. An enum cannot be used to create objects, and it cannot extend other classes though it can implement interfaces.