Enum was introduced in Java 1.5 as a new type whose fields consist of a fixed set of constants.

num Month
{ JAN,FEB,MAR, ... DEC; // ; is optional }

Enum in Java

1). Enum concept introduced in 1.5 versions. 

2). When compared with old languages enum java's enum is more powerful. 

3). By using enum we can define our own data types which are also come enumerated data types.

The internal implementation of enum

Internally enum's are implemented by using the class concept. Every enum constant is a reference variable to that enum type object. Every enum constant is implicitly public static final always.



enum Loan {
	PL,
	HL;
}

coverted to

final class Loan extends java.lang.Enum {
	public static final PL = new Loan();
	public static final HL = new Loan();
}

Declaration and usage of enum

package com.javacodestuffs.core.enums; enum Loan { PL, HL; } class EnumTest1 { public static void main(String args[]) { Loan hl = Loan.HL; System.out.println(hl); } } output: HL

Note: Every enum constant internally static hence we can access by using "enum name". Internally inside every enum toString() method is implemented to return the name of the constant.

Java Enum Important Points

  • All java enum implicitly extends java.lang.Enum class that extends Object class and implements Serializable and Comparable interfaces. So we can’t extend any class in the enum.
  • Since enum is a keyword, we can’t end the package name with it, for example, com.bala.enum is not a valid package name. Enum can implement interfaces.  
  • Enum constructors are always private.
  • We can’t create an instance of an enum using the new operator.
  • We can declare abstract methods in java enum, then all the enum fields must implement the abstract method.
  • We can define a method in enum and enum fields can override them too. For example, the toString() method is defined in the enum, and enum field START has overridden it.
  • Java enum fields have a namespace, we can use enum field only with a class name like ThreadStates.START
  • Enums can be used in the switch statements.
  • We can extend existing enum without breaking any existing functionality. For example, we can add a new field NEW in ThreadStates enum without impacting any existing functionality.
  • Since enum fields are constants, java best practice is to write them in block letters and underscore for spaces. For example EAST, WEST, EAST_DIRECTION, etc.
  • Enum constants are implicitly static and final.
  • Enum constants are final but it’s variable can still be changed.
  • Since enum constants are final, we can safely compare them using "“==" and equals() methods. Both will have the same result.

Enum vs switch statement

Until 1.4 versions the allowed argument types for the switch statement are byte, short, char int. But from 1.5 version onwards in addition to this, the corresponding wrapper classes and enum type also allowed. That is from 1.5 version onwards we can use enum type as an argument to switch statements.


package com.javacodestuffs.core.enums;
enum Loan {
	PL,
	HL,
	BL,
	CL,
	CCL;
}

class EnumTest2 {
	public static void main(String args[]) {
		Beer hl = Loan.HL;
		switch (hl) {

		case CCL:
			System.out.println("Interest rate are veryvery high.");
			break;

		case PL:
			System.out.println("Interest rate are high.");
			break;
		case HL:
			System.out.println("Interest rate are much less.");
			break;
		case BL:
			System.out.println("Interest rate are very less.");
			break;

		case CL:
			System.out.println("Interest rate are less.");
			break;
		default:
			System.out.println("No ther optons for the Loan!!!!");
		}
	}
}
output:

Interest rate are much less.

If we are passing enum type as an argument to switch statement then every case label should be a valid enum constant otherwise we will get a compile-time error.


package com.javacodestuffs.core.enums;
enum Loan {
	PL,
	HL,
	BL,
	CL,
	CCL;
}

class EnumTest3 {
	public static void main(String args[]) {
		Beer hl = Loan.HL;
		switch (hl) {
		case PL:
		case HL:
		case GL:
		}
	}
}
Output:
Compile time error.
H:
\dev\javac Test.java
Test.java:
unqualified enumeration constant name required
case GL:
	


We can declare enum either outside the class or within the class but not inside a method.

If we declare enum outside the class the allowed modifiers are : public,  default, and  strictfp.

If we declare enum inside a class then the allowed modifiers are : 

 public 

 private 

default + protected 

 strictfp 

 static

make code for enum2

Enum vs inheritance:

  • Every enum in java is the direct child class of java.lang.Enum class hence it is not possible to extends any other enum.
  • Every enum is implicitly final hence we can't create child enum.
  • Because of the above reasons we can conclude the inheritance concept is not applicable for enums explicitly. Hence we can't apply extends keyword for enums.
  • But enum can implement any no. Of interfaces simultaneously.

enum3 enum 4 code . .

Java.lang.Enum class

1) Every enum in java is the direct child class of java.lang.Enum class. Hence this class acts as a base class for all java enums. 

 2) It is an abstract class and it is a direct child class of "Object class" 3) It implements Serializable and Comparable.

values() method

Every enum implicitly contains a static values() method to list all constants of an enum. Example: Loan[] loan = Loan.values();

ordinal() method

Within enum the order of constants is important we can specify by its ordinal value. We can find ordinal value(index value) of enum constant by using ordinal() method. Example: public final int ordinal();


package com.javacodestuffs.core.enums;
enum Loan {
	PL,
	HL,
	BL,
	CL,
	CCL;
}

public class EnumTest4 {
	public static void main(String args[]) {
		Loan hl = Loan.HL;
		Loan[] loan = Loan.values();
		for (Loan l: loan) {
			System.out.println(l + " ::::::::> " + l.ordinal());
		}
	}
}

output:
PL ::::::::> 0
HL ::::::::> 1
BL ::::::::> 2
CL ::::::::> 3
CCL ::::::::> 4

 

The specialty of java enum

When compared with old languages enum, java's enum is more powerful because in addition to constants we can take normal variables, constructors, methods, etc which may not possible in old languages. Inside enum, we can declare the main method and even we can invoke enum directly from the command prompt.

package com.javacodestuffs.core.enums; enum Loan { PL, HL, BL, CL, CCL; } class EnumTest5 { public static void main(String args[]) { System.out.println("enum Loan main() method called"); } } Output: H: \dev > java Loan enum Loan main() method called

In addition to constants if we are taking any extra members like methods then the list of constants should be in the 1st line and should end with a semicolon. If we are taking any extra member then enum should contain at least one constant. Any way an empty enum is always valid.

num 6 7 code

Enum vs constructor

Enum can contain a constructor. Every enum constant represents an object of that enum class which is static hence all enum constants will be created at the time of class loading automatically and hence constructor will be executed at the time of enum class loading for every enum constants.

package com.javacodestuffs.core.enums; enum Loan { PL, HL, BL, CL, CCL; Loan() { System.out.println("Constructor of Loan enum is called."); } } public class EnumTest6 { public static void main(String args[]) { Loan hl = Loan.HL; // --->1 System.out.println("loan EMI Enum Test"); } } output: Constructor of Loan enum is called. Constructor of Loan enum is called. Constructor of Loan enum is called. Constructor of Loan enum is called. Constructor of Loan enum is called. loan EMI Enum Test

If we comment on line 1 then the output is loan EMI. We can't create enum objects explicitly and hence we can't invoke constructor directly.

package com.javacodestuffs.core.enums; enum Loan { PL, HL, BL, CL, CCL; Loan() { System.out.println("Constructor called."); } } public class EnumTest7 { public static void main(String args[]) { Loan hl = new Loan(); System.out.println(hl); } } output: EnumTest7.java:15: error: enum types may not be instantiated Loan hl = new Loan(); ^ 1 error

PL => public static final Loan PL = new Loan(); 

PL(100) => public static final Loan PL = new Loan(100);

package com.javacodestuffs.core.enums; enum Loan { PL(11.50), HL(7.50), BL(12.00), CL(13.90), CCL; float interest; Loan(float interest) { this.interest = interest; } Loan() { this.interest = 18.5; } public int getInterest() { return interest; } } public class EnumTest8 { public static void main(String args[]) { Loan[] loans = Loan.values(); for (Loan loan: loans) { System.out.println(loan + "......." + loan.getInterest()); } } } output : PL.......11.5 HL.......7.5 BL.......12.0 CL .......13.9 CCL.......18.5

Inside enum, we can take both instance and static methods but it is not possible to take abstract methods.

Every enum constant represents an object hence whatever the methods we can apply on the normal objects we can apply the same methods on enum constants also.

Which of the following expressions are valid?


Loan.HL==Loan.PL----------------------------> false Loan.HL.equals(Loan.PL) -------------------> false Loan.HL < Loan.PL------------------------------> invalid Loan.HL.ordinal() < Loan.PL.ordinal()------> valid
package com.bala;enum Month { JAN,FEB,MAR, ... DEC; }
package com.hello;
//import static com.bala.*;
import static com.bala.Month.JAN;
class A
{
public static void main(String args[]){
System.out.println(JAN);
}
}
import com.bala.*; ---------------------------->invalid
import com.bala.JAN; ------------------------->invalid
import static com.bala.JAN.*; --------------->valid
import static com.bala.Month.JAN; ---------->valid

enum Month
{
JAN,FEB,MAR,  ... DEC;      //; -->optional
}
 package welcome;
//import com.bala.Month;
import pack1.*;
//import static com.bala.Month.JAN;
import static com.bala.Month.*;
class EnumTest9
{
public static void main(String args[]){
Month jan = Month.JAN;
System.out.println(MAR);
}
}

Note : If we want to use class name directly from the outside package we should write normal import, If we want to access the static method or static variable without class name directly then static import is required.

package com.javacodestuffs.core.enums; enum Color { BLUE, RED, GREEN; public void info() { System.out.println("Universal color"); } } public class EnumTest10 { public static void main(String args[]) { Color[] c = Color.values(); for (Color c1: c) { c1.info(); } } } output: Universal color Universal color Universal color

package com.javacodestuffs.core.enums; enum Color { BLUE, RED { public void info() { System.out.println("Dangerous color"); } }, GREEN; public void info() { System.out.println("Universal color"); } } public class EnumTest11 { public static void main(String args[]) { Color[] c = Color.values(); for (Color c1: c) { c1.info(); } } } output: Universal color Dangerous color Universal color

enum Vs Enum Vs Enumeration 

enum: enum is a keyword that can be used to define a group of named constants. 

 Enum : It is a class present in java.lang package. Every enum in java is the direct child class of this class. Hence this Enum class acts as a base class for all java enums. 

 Enumeration : It is an interface present in java. util package. We can use Enumeration to get the objects one by one from the Collections.

Post/Questions related to  Enum in Java

How to get value from enum in java?
How to use enum constructor in java?
How to get enum key from the value in java?
How to convert the enum to list in java?
Attach Values to Enum in Java
How to pass enum as a parameter in java?
How to check enum contains a value in java?
How to use enum in switch case java?
How to override valueof in enum java?
What is the difference between iterator and enumeration in java?
What is the advantage of enum in java?

Enum in Java with methods, its valid modifiers, important points about Enum. We also have seen various examples of the enum, where it can be used. All source code in the article can be found in the GitHub repository.