What is Java Enumeration or Difference between Java Enum & class


Java Enum or Enumeration is special construct which is used to define group of Named Constants.It is like our data type having some range which is named constants.It comes after java 1.5.

In Java we have data type like integer which is having values from -32768 to 32767 similarly we have Data type called Enum & its range or values are whatever we define as named constants.

Enum Week{

MON, TUE, WED, THU, FRI, SAT, SUN ; ( semicolon is optional)

}

Apart from Named constants you can have constructor, method or variable as well. So its little different then other language like C++ Enums. Java Enum is more flexible & useful then just a way to used Named Constants group. Enum internally will converted to class only & its enum variable will be public static final only . Every constants will be Enum type only.


Enum Week{

MON, TUE, WED, THU, FRI, SAT, SUN ; ( semicolon is optional)

}

can be seen as below as well internally.

class Week{

Public static final MON = new Week ();
Public static final TUE =  new Week ();
Public static final WED =  new Week ();
Public static final THU =  new Week ();

}



For accessing Enum we have to use like Week.MON.

public static void main(String args[]){

Week w = Week.MON
System.out.println(" Mon Enum value is "+w ); // output is MON

}


Comments

Popular posts from this blog

Conversion from Clob To String in java and Vice versa

Portable Java 8/ JDK8 setup without admin rights

Multi Threading , Producer consumer problem in Java