What is Enum in Java

Connect with

Oracle Java
What is enum in java? Enum in Java is a keyword, a feature which is used to represent fixed number of well-known values.

Key Points

• Enums are implicitly declared public, static, and final, which means you cannot extend them.
• When you define an enumeration, it implicitly inherits from java.lang.Enum. Internally, enumerations are converted to classes.
• Enums are a typesafe way to achieve restricted input from users.
• You cannot use new with enums, even inside the enum definition.
• Enum classes are by default final classes.
• You can apply the valueOf() and name() methods to the enum element to return the name of the enum element.
• If you declare an enum within a class, then it is by default static.
• You cannot use the new operator on enum data types, even inside the enum class.
• You can compare two enumerations for equality using == operator.
• When an enumeration constant’s toString() method is invoked, it prints the name of the enumeration constant.
• The static values() method in the Enum class returns an array of the enumeration constants when called on an enumeration type.
• Enumeration constants cannot be cloned. An attempt to do so will result in a CloneNotSupportedException.
• If enumeration constants are from two different enumerations, the equals() method does not return true.
• A constructor in an enum class can only be specified as private.

Enum avoids magic numbers, which improves readability and understandability of the source code. Also, enums are typesafe constructs. Therefore, you should use enums wherever applicable.

Example of Enum


/**
 * @author ranjeet
 *
 */
public enum TransactionStatus {

	TXN_FAILURE(1) , 
	TXN_SUCCESS(2),
	TXN_PENDING(3);		
	
	private final int identity;

	TransactionStatus(int identity) {
		this.identity = identity;
	}

	public int getIdentity() {
		return identity;
	}
	
	public static int getValueOf(TransactionStatus status) {
		return status.getIdentity();
	}
}


Connect with

2 thoughts on “What is Enum in Java

  1. Pingback: kabita
  2. Pingback: nancy

Leave a Reply

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