Initialisation of Static variables in java

I was asked this question in an interview

If you do something like this,

    private int c = d;
    private int d;

It results in compile-time error that you

Cannot reference a field before it is defined.

Coming to the interview question,

    1  public static int a = initializeStaticValue();
    2  public static int b = 20;


    3  public static int initializeStaticValue() {
    4   return b;

       }

    5   public static void main(String[] args) {
           System.out.println(a);
           System.out.println(b);
        }

I gave the same response as a gets initialised by a call to initializeStaticValue() where it is referencing an undefined value b.

But the programs works fine, gets compile, and prints

0
20

I am confused why

Cannot reference a field before it is defined. 

was not thrown.

Secondly, when i debug it, why the control lands at

3  public static int initializeStaticValue() {

I mean, why this is the starting position of the program.

Upvotes: 3

Views: 95

Answers (1)

Adrian Shum
Adrian Shum

Reputation: 40066

If you are concerned about the order of initialization/execution, here is what is going to happen (I believe it is not very accurate, just giving you an idea):

  1. JVM is asked to run the Java app (assume your class is named) Foo, it tries to load Foo class from classpath
  2. Foo is loaded, with static variables assigned with default value (0 for int)
  3. Static initializers will be executed, first running that on line 1 which in turn calls initializeStaticValue() which returns the value of b at this moment (0), and assigns it to a
  4. Static initialization continues, and comes to line 2. It assigns b with 20.
  5. Foo is successfully loaded & initialized, and JVM calls Foo.main()

Upvotes: 5

Related Questions