Home » Java » Core Java » Java Enum puzzler

About Attila Mihaly Balazs

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 our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....

Leave a Reply

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

*


9 − six =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Do you want to know how to develop your skillset and become a ...

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!
Get ready to Rock!
To download the books, please verify your email address by following the instructions found on the email we just sent you.

THANK YOU!

Close