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.

Related Whitepaper:

Bulletproof Java Code: A Practical Strategy for Developing Functional, Reliable, and Secure Java Code

Use Java? If you do, you know that Java software can be used to drive application logic of Web services or Web applications. Perhaps you use it for desktop applications? Or, embedded devices? Whatever your use of Java code, functional errors are the enemy!

To combat this enemy, your team might already perform functional testing. Even so, you're taking significant risks if you have not yet implemented a comprehensive team-wide quality management strategy. Such a strategy alleviates reliability, security, and performance problems to ensure that your code is free of functionality errors.Read this article to learn about this simple four-step strategy that is proven to make Java code more reliable, more secure, and easier to maintain.

Get it Now!  

Leave a Reply


× six = 54



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
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.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books