4

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


}
Shakeeb Ayaz
  • 6,200
  • 6
  • 45
  • 64

5 Answers5

13

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

Marian Paździoch
  • 8,813
  • 10
  • 58
  • 103
alex
  • 6,359
  • 1
  • 23
  • 21
2

Following way to execute the blocks....

1 := Static declaration.

2 := Non-Static declaration.

3 := Constructor execution.

4 := Methods execution.

Mr.Sandy
  • 4,299
  • 3
  • 31
  • 54
1

Static block is executed first.

Static block is executed even if only a static field is accessed without instantiating an object. In this scenario constructor or class method (onCreate) are nor executed yet, if only static field is accessed.

All static code is executed when the Class object is created. This (Class) object physically holds static variables (class variable) in the memory. Static block can be initialization for Class object. Later every class instance accesses static vars in the Class object.

Constructor is also a static method internally since it's called before the object is instantiated.

This link goes into more details if you'd like to study it further: http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

MSquare
  • 6,311
  • 4
  • 31
  • 37
0

Static block.

Remember an android program is primarily a java program. A static block is used for pre-initialization at the time of class loading and hence would be called before onCreate in android.

see this for more details: http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html

Gagan
  • 1,497
  • 1
  • 12
  • 27
0

First static is called and then onCreate is called

prvn
  • 916
  • 5
  • 5