Java: Example Enum
This article contains a variety of example enums (enumerations) in use.
Simple Enum
The example below is a simple enum example related to temperature.
// enum definition
enum Heat {
COLD("Cold"),
WARM("Warm"),
HOT("Hot");
String label;
Heat(String label) {
this.label = label;
}
public void print() {
System.out.println(label);
}
}
// enum usage
Heat myVar = Heat.WARM;
myVar.print();
// output: "Warm"
Enum Within a Class
The example below contains an enum being used within a class.
public class MyClass {
enum Heat {
COLD("Cold"),
WARM("Warm"),
HOT("Hot");
String label;
Heat(String label) {
this.label = label;
}
public void print() {
System.out.println(label);
}
}
public static void main(String[] args) {
Heat myHeat = Heat.COLD;
System.out.println(myHeat);
myHeat.print();
}
}
Enum Within a Switch Statement
The example below contains an enum being used within a switch statement.
enum Heat {
COLD,
WARM,
HOT
}
public class EnumExample {
public static void main(String[] args) {
Heat myVar = Heat.HOT;
switch(myVar) {
case COLD:
System.out.println("ice coooollllld!!!");
break;
case WARM:
System.out.println("nice and cozy");
break;
case HOT:
System.out.println("so hot right now!!");
break;
}
}
}
Loop Through an Enum
The example below loops through an enum to print out its values.
for (Heat temp : Heat.values()) {
System.out.println(temp);
}
Use a Parameterized Enum
The example below uses a parameterized enum.
public class EnumDemo {
public enum TripCosts {
FLIGHTS(700),
HOTELS(500),
FOOD(300),
ACTIVITIES(250);
TripCosts(int price) {
this.price = price;
}
private final int price;
public int getPrice() {
return price;
}
}
public class UsingParameterizedEnum {
public static void main(String[] args) {
for (TripCosts f : TripCosts.values()) {
System.out.print("TripCosts: " + f + ", ");
if (f.getPrice() >= 4) {
System.out.print("Expensive, ");
} else {
System.out.print("Affordable, ");
}
switch (f) {
case FLIGHTS:
System.out.println("Flights are expensive");
continue;
case HOTELS:
System.out.println("You're staying VIP!");
continue;
case FOOD:
System.out.println("Good thing you like to each cheap!");
continue;
default:
System.out.println("Option not found. Enjoy your trip!");
}
}
}
}
Summary: Enumeration Examples
- Enumerations (aka "enums") are very helpful for defining and using a fixed set of values instead of relying upon developers to set corresponding transient variables
- Enumerations are easy to create
- Enumerations are easy to use