This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
All static members get initialized first because static members are initialized when the class is first time loaded. Remember static variables are class members NOT instance members. All instance members are initialized when the object is constructed, using new operator. Even i, is a final variable, it's still an instance member so get initialized when the constructor is ran and can't be changed after.
If you decompile your code you will see something like this:
Probably you were thinking to static final variables, which are also called compiled time constants which is totally something else. A final variable IT IS NOT a compile constant. To be a compile time constant static keyword need to be added(static final) and the variable need to be a primitive or to have a wrapper type.
All instance members are initialized when the object is constructed, using new operator. Even i, is a final variable, it's still an instance member so get initialized when the constructor is ran and can't be changed after
what you say right now is right, but not always, take this code :
and the output is :
before Object creation: i :12 j :2 a :0 After object creation: i :12 j :2 a :12
if you remove the final key word, you have sth like this
before Object creation: i :0 j :2 a :0 After object creation: i :12 j :2 a :12
that means that final members are initialized before the constructor is run. (correct me if i am wrong ), but before or after the static? this what i search.
Joined: Apr 21, 2008
Static variables gets initialized BEFORE instance variables. What you did there doesnt make sense. That init method is ran inside the constructor, so you can't say it's before the constructor. You actually do samething in both places. Final instance variables get initialized before non-final instance variables, but not before static variables. These are the steps when you call the constructor for your object InitialTest:
1. All static variables get initialized with their given values or default values. 2. All instance variables get initialized with their default values. Final instance variables get initialized with the given value. 3. super() constructor is ran. 4. All instance variables get init with their given values.
That's how the compiler transform your class:
The order will be like this: 1. static final variables 2. static variables 3. final variables 4. non-final non-static variables