StackOverflowed
StackOverflowed

Reputation: 5975

Static field lifespan in Android

Quick question, but one I can't find an answer to in the documentation.

What is the lifespan of a static field in an Android App? When is it initialized and when is it destroyed? Does the final attribute modify its lifecycle? What about private/public? Do they live as long as the Application instance is alive?

Take two instances:

public class DemoClass {
   static int one = 1;
   static int three = DemoActivity.two + one;
}

public class DemoActivity extends Activity {
     public static int two = DemoClass.one + DemoClass.one;
     private static final int four;
     public static int five;

     public void onCreate(Bundle b) {
          four = two + two;
          five = DemoClass.three  + DemoClass.one + DemoClass.one;

     }

}

Edit: Also what about static dictionaries?

For instance,

public class AnotherDemoActivity extends Activity {
public static ArrayList<String> strings = new ArrayList<String>();

@Override public void onCreate(Bundle b) {
   strings.add("test");
   strings.add(new String("another test");
   strings.add(new DemoClass());
}

How long will the "strings" elements live for?

Upvotes: 1

Views: 619

Answers (2)

kosa
kosa

Reputation: 66637

  • static scope is till the class is un-deployed. It will be
    initiated on initiation (right after load ).
    No. final attribute doesn't modify above behavior.

Upvotes: 1

Ian Warwick
Ian Warwick

Reputation: 4784

When is it initialized and when is it destroyed?

It is initialized when the class that declares it is loaded, It will survive until your application process ends.

Does the final attribute modify its lifecycle?

No

What about private/public?

No

Do they live as long as the Application instance is alive?

Yes

Upvotes: 5

Related Questions