Question

Is there a reason where static final variable will not be instantiated before the static block?
So in the example I provided will print:

someVar value= null

Instead of:

 someVar value=SomeValue


I saw this behavior today, In my application,
I am trying to reproduce - unsuccessfully - I do see the value of the static member...

class SomeClass{
    static final String someVar ="SomeValue";

    static{
         System.out.println("someVar value=" + someVar );
   }

public static void main(String[] args){     
    new SomeClass();
}

}
Was it helpful?

Solution

The order of initialization is given in JSL #12.4.2:

For static initialization:

  • Execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.

For construction:

  • Evaluate the arguments and process that superclass constructor invocation recursively

  • Execute the instance initializers and instance variable initializers for this class, assigning the values of instance variable initializers to the corresponding instance variables, in the left-to-right order in which they appear textually in the source code for the class.

  • Execute the rest of the body of this constructor.

Note that initializer blocks and variable initializers are considered together, not separately.

OTHER TIPS

I would to say, it depend on your code sequence. Run following code in your local, it will tell you the answer.

public class SomeClass{
    static final String someVar ="SomeValue";
    static final StaticMember staticMem = new StaticMember(1);

    static{
        System.out.println("someVar value=" + someVar );
    }

    static final StaticMember staticMem2 = new StaticMember(2);

    public static void main(String[] args){     
        new SomeClass();
    }

}

class StaticMember {
    StaticMember(int num) {
        System.out.println("StaticMember constructor " + num);
    }
}

There is an order the jvm will excecute and instanciate always in this priority:

  1. Static Blocks
  2. Static Members
  3. Instance Blocks
  4. Instance Members
  5. Constructor

If you have inheritance the instanciation order will be a little bit different:

  1. Parent Static Block
  2. Parent Static Members
  3. Child Static Block
  4. Child Static Members
  5. Parent Non-Static Members
  6. Child Non-Static Members
  7. Parent Constructor
  8. Child Constructor

I hope this clarifies a little your issue.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top