Practice Problems on enum – Set1

      No Comments on Practice Problems on enum – Set1




What would be the output of the below Program : Problems on enum??

The below problems on enum is based on classloading of enum classes.

MONTHS.java

package com.masterjavatutorial;
public enum MONTHS {
    JANUARY,FEBRUARY,MARCH,APRIL,
    MAY,JUNE,JULY,AUGUST,
    SEPTEMBER,OCTOBER,NOVEMBER,DECEMBER;

    MONTHS(){
	System.out.println("HelloWorld");  
    }
	
}

Example.java

package com.masterjavatutorial;
public class Example {
   public static void main(String[] args) {
       MONTHS month = MONTHS.JANUARY; 
       System.out.println(month); 

       MONTHS month1 = MONTHS.AUGUST; 
       System.out.println(month1); 

   }

}

Output of the above program is as below:

HelloWorld
HelloWorld
HelloWorld
HelloWorld
HelloWorld
HelloWorld
HelloWorld
HelloWorld
HelloWorld
HelloWorld
HelloWorld
HelloWorld
JANUARY
AUGUST

Why this Output??

when this statement (MONTHS month = MONTHS.JANUARY;) is encountered by JVM , JVM checks whether class is loaded or not. If not, then it would load the class. When JVM loads the class for the first time and during loading for each of the enum constants, it executes enum constructor for each of the constants.

When JVM encounters the statement (MONTHS month = MONTHS.JANUARY;), then it checks whether MONTHS.class is loaded or not. Since, it has already been loaded, so execution of constructor does not occur again for each of the constant.

Hence, the output of the above program is like that.