Initializing 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;

      

This results in a compile-time error you

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 answer, which is a

initialized by calling initializeStaticValue () where it refers to an undefined value b

.

But the programs work fine, compile and print

0
20

      

I am confused why

Cannot reference a field before it is defined. 

      

not thrown away.

Second, when I debug it, why does the control land on

3  public static int initializeStaticValue() {

      

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

+3


source to share


1 answer


If you are worried about the order of initialization / execution, here's what happens (I find it not very accurate, just giving you an idea):



  • The JVM was asked to start a Java application (assuming your class is named) Foo

    , it tries to load the class Foo

    from the classpath
  • Foo

    loaded with static variables assigned with a default value (0 for int)
  • Static initializers will execute by first running this on line 1 which in turn calls initializeStaticValue()

    which returns the value b

    at that moment (0) and assigns ita

  • The static initialization continues and goes to line 2. It assigns b

    20.
  • Foo

    successfully loaded and initialized and the JVM calls Foo.main()

+5


source







All Articles