Reputation: 487
I have a little confusion over data initialization in Java. I have read that, before any method is called in Class all class fields will be initialized first.
consider this:
public class TestCls {
public static int test = getInt();
static{
System.out.println("Static initializer: " + test);
}
public static int getInt(){
System.out.println("giveInt func: " + test);
return 10;
}
public static void main(String... args){
System.out.println("Main: " + test);
}
Output:
giveInt func: 0
static initializer: 10
main: 10
Here 'test' field get its value by invoking getInt() function which resides in same class. But when getInt() is called 'test' field will be initialized to default value i.e 0 (see inside getInt() function). My question is when will getInt() function will be called? Will it be called at the time of defining 'test' field or at the last after initializing all fields in the class.
Upvotes: 4
Views: 75
Reputation: 96385
You can test this by adding some more fields.
public class TestCls {
public static int test = getInt();
public static int moreJunk = initializeMoreJunk();
static{
System.out.println("Static initializer: test=" + test + ", moreJunk=" + moreJunk);
}
public static int getInt(){
System.out.println("giveInt func: " + test);
System.out.println("moreJunk=" + moreJunk);
return 10;
}
public static int initializeMoreJunk() {
return -1;
}
public static void main(String... args){
System.out.println("Main: " + test);
}
}
with output of:
giveInt func: 0
moreJunk=0
Static initializer: test=10, moreJunk=-1
Main: 10
This shows that class variables get initialized to their default values first (primitive ints default to 0), then initialization blocks and methods get called, proceeding from the top of the class downward.
Upvotes: 1
Reputation: 38300
Here is what happens in your code above.
This results in the (correct) output that you see.
Upvotes: 3