Reputation: 6251
If have a class like this
public static class Globals {
public static string MyString;
static Globals() {
MyString = "example";
}
}
will MyString always be "example" as long as the app process is running (possibly in background)?
-- EDIT --
Assume that MyString is not changed by the user.
Upvotes: 1
Views: 301
Reputation: 6930
Yes, as long as the process exists. Be careful what references you keep to avoid memory leaks. See:
Lifetime of a static variable in Android and Static singleton lifetime in Android.
You can extend Application class for this purpose as well.
Upvotes: 1
Reputation: 262474
It is a public
, non-final
field, so no, there could be all sorts of code that changes its value.
But yes, if you don't change the value, it will stay set. The initializer block is run once when the class itself is loaded, and the field will not somehow magically lose its value. (Even if the class should get unloaded, which I am not sure can ever happen on Android, the field would get re-initialized if the class should get loaded again)
Upvotes: 2