Why do you think it makes more sense for each instance of a class to have its own copy of a constant value. Or to put it a different way, just because some data is constant regardless of the state of an object, it doesn't mean that an object's state shouldn't access that data.
Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
posted 12 years ago
but to free up memory that the variable would hold, no matter how small, is better,
i.e. setting the variable to non-static only creates and sets the variable when the class is booted up, like there is no need to set the variable as static and just to use it within a non-static instance?
If a variable is static, then there's one copy, and one copy only.
If it's not, then every single object has its own copy.
I don't understand how making many copies of something qualifies as "freeing up memory" -- unless you've got a class the average number of instances of which is near zero.
But the funny thing is that if the variable is non-static, and it's initialized in a constructor or initializer, then the code that does that initialization has a reference to a single copy of the data -- i.e., a static copy -- that is used to do that initialization. So even if the variale is non-static -- there's a static copy of the data!
Originally posted by Campbell Ritchie: I think it's the other way round; when an instance is garbage collected its fields are lost, but static members are retained in memory until the class and its class loader are garbage collected.
Yes, primitives and references are. But if it's a non-final reference then it can be set to null, and the object can be garbage collected if there are no other references.