I have a little confusion about data initialization in Java. I read that before calling any method in the class, all the fields of the class 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);
}
Exit:
giveInt func: 0
static initializer: 10
main: 10
Here the 'test' field gets its value by calling the getInt () function, which is in the same class. But when getInt () is called the "test" field, the default value ie 0 will be initialized (see. The internal function getInt ()). My question is when will the getInt () function be called? Whether it will be called during the definition of the "test" field or at the end after the initialization of all fields in the class.
Muthu source
share