This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
The explanation provided by the book is very detail (and very enlightening, if I may add). What is it about the explanation that is still confusing to you? We can't elaborate on the answer, if you don't tell us what you don't understand about the answer.
Static initializers are executed in declared order. So in this case, INSTANCE is initialized first, then CURRENT_YEAR. However, Elvis needs CURRENT_YEAR but it hasn't been initialized yet. Because the JVM simply does not initialize CURRENT_YEAR right there and then its default value is used.
raj chiru wrote:
Actually where I'm confusing is,we are explicitly declared the static field values,right?But why First,static fields are set to default values?
Well, which is worse? A default value or an undefined random value?
From this puzzle, you can see that initialization is not atomic, and it is possible to see variables before they get assigned. So, yes. Static fields are set to default values -- because the values is not known yet. But that is better than an undefined random value, which is what it would be seen as if the variable isn't set.
BTW, there is an exception to this rule. If the static variable is a compile time constant, then the value is guarranteed to be known before it is used -- and it will be set correctly to the compile time constant value.