views:

84

answers:

2

Why is the use of static final variables encouraged to declare constants over just final variables? The use of static sounds logical when there will be many instances of a class but is this argument correct when used for a Android activity. In fact, since the Class instance will be around even after the activity finishes and is eventually garbage collected, it seems like all these constants will still be in memory until the class loader is around.

Also, does the compiler inline non-static final variables(ints and String) just like it does for static final variables?

+2  A: 

They're static so that you can read them from other classes. Static constants are mostly used for sending broadcasts and things like that. And there may very well be many instances of an Activity.

Falmarri
Agreed. However, if I just want to declare constants in an Activity which are not going to be used outside it and if I have around 20 -25 string constants should I declare them static? All these constants will hang around until the class loader is reclaimed. On the other hand if I just declare them final and non-static they will go away when the activity is GCed. There might be many instances of the activity but only if the user visits the activity repeatedly in quick succession. But isn't this rare?
adityad
Not necessarily. It has nothing to do with how fast the user visits the activity. Having multiple instances of the same activity is perfectly valid in Android and is the default behavior. As for your question, if the strings have no use outside of the instance, then don't declare them static. If they're going to be the same across all instances, you're probably better off declaring them static. In mobile devices CPU operations are more important than memory use (imo), and you'll save CPU cycles by using static variables rather than having them created every instance. Although it's negligible
Falmarri
+2  A: 

Another point is that you don't even need to create an Object of the class to access the constant. For example, if you want to get PI you don't need to create an instance of the Math class first, it's sufficient to use the class itself

Log.d("LogTag", String.valueOf(Math.PI));
Martin