Enums in Java

Arivuselvan Chinnasamy
2 min readApr 30, 2021

--

An enum type (short for enumeration) is a special data type introduced in Java 1.5 to hold a set of predefined constants. For example, representing an Order Status as PENDING, DELIVERED etc or Gender of Person as MALE, FEMALE, or OTHERS etc.

Enum can be defined either as part of class like other variables or in independent class using enum keyword, followed by enum name and then its fields in uppercase letters. For example, the order status values can define as,

enum Order_Status {PENDING, FAILED, PROCESSING, COMPLETED, CANCELLED, REFUNDED}

The enum can be created in a separate class.

package com.arivu.enums;public enum Order_Status {   PENDING, FAILED, PROCESSING, COMPLETED, CANCELLED, REFUNDED;
}

The enum can be accessed as shown below,

Order_Status orderStatus = Order_Status.PENDING;
System.out.println("Order_Status name: " + orderStatus.name());
System.out.println("Order_Status using valueOf name: " + Order_Status.valueOf("COMPLETED"));

In below snippet, I have showed how the enums can be used with Switch statement.

Order_Status  orderStatus = Order_Status.REFUNDED;
switch(orderStatus) {
case PENDING :
System.out.println("Your order is in Pending status");
break;
case FAILED :
System.out.println("Your order is in Failed status");
break;
case PROCESSING:
System.out.println("Your order is in Processing status");
break;
case COMPLETED:
System.out.println("Your order is in Completed status");
break;
case CANCELLED:
System.out.println("Your order is in Cancelled status");
break;
case REFUNDED:
System.out.println("Your order is in Refunded status");
break;
}

The static values method in enum can be used to retrieve all of the values of the enum in an array. For ex,

for(Order_Status order_status : Order_Status.values()) {  System.out.println("Order_Status : name " + order_status.name());}

In Java 8 later, the Streams also can be used.

Arrays.stream(Order_Status.values()).forEach(System.out::println);

The enums can also have constructor like a Class in Java. I have modified the Order_Status enum to have constructor as shown below,

--

--

No responses yet