Muthu
Muthu

Reputation: 487

confusion over data initialization in Java

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

Answers (2)

Nathan Hughes
Nathan Hughes

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

DwB
DwB

Reputation: 38300

Here is what happens in your code above.

  1. The class is created and all static class level variables (properties, data members, what ever you want to call them) are initialized to the appropriate initial value (0 for int, null for object references).
  2. Starting from the top, static initialization blocks are executed.
  3. The main method is entered.

This results in the (correct) output that you see.

Upvotes: 3

Related Questions