Search code examples
androidandroid-activityoncreate

which one is called first static block or oncreate method?


I want to know which is executed first static block or Oncreate method

public class MainActivity extends Activity {
static{
// dosomething
}


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


}

Solution

  • To answer your question, the static block, then the onCreate method.

    A class is loaded like this

    • First, any thing static, in the order it is defined.
    • Then, anything non static.
    • Then, a contructor
    • Then, instance methods can be called.

      public class Example {

      public static int FIRST = 1;
      
      static {
          // second
      }
      
      public int third = 3;
      
      {
          // forth
      }
      
      public Examle(){
          // fifth
      }
      
      public void sixth(){
      }
      

      }

    http://javarevisited.blogspot.com/2012/07/when-class-loading-initialization-java-example.html