Java Enum puzzler

Let’s suppose we have the following code:

enum Case {
   CASE_ONE,
   CASE_TWO,
   CASE_THREE;
   private static final int counter;
   private int valueDependsOnCounter;
   static {
     int sum = 0;
     for(int i = 0; i<10; i++) {
       sum +=i;
     }
     counter = sum;
   } 
   Case() {
     this.valueDependsOnCounter = counter*counter;
   }
 }

What do you think is the result of compiling and running the code?

  1. Compiler error
  2. Runtime error
  3. Runs ok but valueDependsOnCounter has a strange value
  4. Runs ok

Give it a second of thought. (Spoiler block) The answer is the 8th letter in the following sequence: bdcadcbabcad.
To shed a light on this it’s neccesary to review the following:
A. The order of static initalization inside a class:

  1. static viaribales in the order they apear
  2. static blocks in the order they apear
  3. instance variables in the order theyappear
  4. constructors

B. The order of constructor calling (this aplies to the statics as well):

  1. super classes
  2. local class

C. The way in which a enum object is represented in java:

1) An enums of name E is a class that among others, has an *implicit* static final field named n of type Efor every member of the enum. More specificaly, the Caseclass could be written in the following way:

   enum Case {
 

     public static final Case CASE_ONE;
 

     public static final Case CASE_TWO;
 

     public static final Case CASE_THREE;
     

     …
 

     }
 
 

2) The above members apear in the order they are declared and are located above all the other static members of the enum (that means they are the first ones to be initialized).
3) The enum constant is said to be created when the corresponding field is initialized.

So the compiler gives an error something like ”It is illegal to access static member counter from enum or instance initializer.”. This is because the order in which the enums are initialized:
1)public static final Case CASE_ONE;
2)public static final Case CASE_TWO;
3)public static final Case CASE_THREE;
4)public static final counter;
5)

 static {
       ..
     counter = something;

     }  
 

6)

 Case() {
       this.valueDependsOnCounter = counter*counter;
     }
  

The first thing that needs to be done is init the CASE_ONE but that would have to call the Case() constructor which in turn depends on the counter which is only initialized in the static {} block (but which hasn’t been executed yet). Now accessing a static from a constructor would be a huge limitation but this is what this flow somehow suggest, that you cannot use statics in a constructor of an enum. Luckly, this is not quite right. What the error is actually trying to tell us is that ”It is a compile-time error to reference a static field of an enum type that is not a *compile-time constant * from constructors, instance initializer blocks, or instance variable initializer expressions of that type.”. The compiler does in fact allow access to statics fields in a enum constructor but only for those that it can compute staticaly (as an optimization mechanism). If we had:

 enum Case {
 
   CASE_ONE,
 
   CASE_TWO,
 
   CASE_THREE;

   private static final int counter = 0;
 
   private int valueDependsOnCounter;  
 
   Case() {
     this.valueDependsOnCounter = counter*counter;
   }
 
 }
 

, all would have been fine since the compiler could have predicted the initalization of counter, use it in the constructor, build the enum instance, and assign it to the static final CASE_ONEvariable. But since counter depends on some hard to predict computation, an error is raised.

There are two solutions for this problem, in order to still have the code work:

1) Put the statics that you need in a nested class and access them from there:

 class Nested {
 
   private static final int counter;

   static {
 
     int sum = 0;

     for(int i = 0; i<10; i++) {
 
       sum +=i;


     }
 
     counter = sum;
 

   }

  }
 
 enum Case {
 
   CASE_ONE,
 
   CASE_TWO,
 
   CASE_THREE;
 

   private static final int counter; 

   private int valueDependsOnCounter;    
 
   Case() {
 

     this.valueDependsOnCounter = Nested.counter*Nested.counter;
 
   }

 } 

2) Initialize in a static block not in the constructor (recomended):

 enum Case {

   CASE_ONE, 

   CASE_TWO,

   CASE_THREE; 

   private static final int counter;
 
   private int valueDependsOnCounter;    
 
   static {
 
     int sum = 0;
 
     for(int i = 0; i<10; i++) {
 
       sum +=i;

     }

     counter = sum;
 
     for(Case c : Case.values()) {
 
       c.valueDependsOnCounter = counter*counter;
 
     }
 
   }
 
 }
 

The exception discussed is even specified in the JAVA specification document.

Reference: Enum puzzler from our JCG partner Attila-Mihaly Balazs at the Transylvania JUG blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

Leave a Reply


one − 1 =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close