What is Enum in Java

Connect with

What is Enum in JavaLearn different aspects of what is enum in java? Enum in Java is a keyword, a feature that is used for constant.

1. Key Points of What is Enum in Java

  • In Java Enums are implicitly declared static, public, and final, which means you can’t extend them in any of your java class.
  • When you define an Enum, by default it implicitly inherits from java.lang.Enum. Internally, enumerations are converted to classes.
  • Enums are a typesafe way to achieve restricted input.
  • You can’t use new keywords with enums, even inside the enum definition.
  • 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 can’t 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.
  • A constructor in an enum class can only be specified as private.
  • Enume can’t be cloned. If you try to do so will result in a CloneNotSupportedException.
  • If enumeration constants are from two different enumerations, the equals() method does not return true.

Above key points helps in understanding of what is enum in java.

2. Enum in Java

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.

3. Example of Enum in Java

Example of Enum

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();
	}
}

4. Reference

Oracle Java Official Site for more details.
I hope you enjoyed what is enum in Java, you can visit core Java tutorial for more details.
Happy learning! 🙂


Connect with

2 thoughts on “What is Enum in Java”

  1. Pingback: kabita

  2. Pingback: nancy

Leave a Comment

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