aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes static var. and static blcok, which is initialized first? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "static var. and static blcok, which is initialized first?" Watch "static var. and static blcok, which is initialized first?" New topic
Author

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

Moya Green
Ranch Hand

Joined: Jan 24, 2002
Posts: 49
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

Joined: Mar 22, 2002
Posts: 1055
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

Joined: Jan 24, 2002
Posts: 49
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

Joined: Mar 22, 2002
Posts: 1055
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

Joined: Jul 03, 2001
Posts: 2120
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.


SCJP2. Please Indent your code using UBB Code
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: static var. and static blcok, which is initialized first?