Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static var. and static blcok, which is initialized first?

 
Moya Green
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I saw the following at http://www.coderanch.com/t/386934/java/java/static
-------------------------------------------------
All statics are processed/initialized in the order that they appear in the code. And they "execute" before main(), and the
constructor(s). Then all non static variables are initialized
-------------------------------------------------
I thought most of time
static variables were initialized first
than static block
then constructor.... It is NOT processed in the order that they appear in the code. Maybe I am wrong. Please help me clarify.
If static block appears before static var., which one is initialized first?
Thank you!
Moya
 
Anthony Villanueva
Ranch Hand
Posts: 1055
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A static block cannot make a forward reference to static variables that are defined after its definition. For example,

the compiler will complain. Is that what you meant?
 
Moya Green
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Anthony,
Thnak you for your quick reply. Your explanation is very helpful. So it is NOT right to say:
All statics are processed/initialized in the order that they appear in the code.
Am I right? Many thanks again. :roll:
Moya
[ September 13, 2002: Message edited by: Moya Green ]
 
Anthony Villanueva
Ranch Hand
Posts: 1055
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Moya Green:
So it is NOT right to say:
All statics are processed/initialized in the order that they appear in the code.

Good gracious, no. All statics are processed/initialized in the order that they appear in the code is correct.
You can test this:

Please rearrange lines 1,2,3,4 in any order you wish and you will see they they execute in the order in the code.
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Using javap -c MyClass it's possible to see that the compiler gathers in textual order the code that initializes static fields, and the one that compounds static initializers (blocks) and places it within a method called clinit. This method is responsible for "initializing" the class.
static final fields that are known by the compiler to have a constant value aren't collected within this method.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic