Puneet Chaurasia Puneet Chaurasia - 2 months ago 20
Java Question

private static final String or private final String

For a Singleton class, is it a good idea to keep String constants (used internally in the member functions) as

private static final
or
private final
?

I want to know more in terms of difference in class's memory footprint for a long running application and otherwise.

Note : I know how
static
and
final
affect a variable. My question is specific to Constants that are used as
private
to the class. More specifically - about there lifetime. Even when there is no object of that class lying in memory.

Answer

There is not much difference between those, only that the private static final String gets initialized when the program gets initialized, the private final String gets initialized when the Singletons instance is being created.

The only advantage of the static String is, is that you can use it in static methods too (if you need them)

Also there are no performance issues with both of them, as both variables won't get garbage collected as long as the program is running.