I have a class that looks like:
public class BadCodeStyle {
private static String theAnswer = null;
public static void setAnswer(String whatsNew) {
theAnswer = whatsNew;
}
public static String getAnswer() {
return (theAnswer == null) ? "I don't know" : theAnswer;
}
}
Of course that's a simplification of the actual class. What really happens is that the static method retrieves a framework object if the variable is null. Setting the variable just serves to insert a mock value for test runs where I want to isolate the code from the framework (retrofitting code for testability is fun - like poking your own eye type of fun).
When I do BadCodeStyle.setAnswer("42")
the static method behaves like a Singleton (?). I did read the classloader explanation and conclude: the variable will stay as long as the class is loaded and that would be as long as the JVM runs? Is that correct?
static is a variable. The value can change, but the variable will persist throughout the execution of the program even if the variable is declared in a function.
A static variable continues to exist and retains its most recent value.
Static variables have a program lifetime. It is created into static memory during compile time and it will be deleted after completion of the program. Hence the correct answer is till the end of the main program. The static variable default value is Zero.
Static variables belong to the class instead of to the individual instances, so it doesn't change in every instance - it only exists in one place. It may give the appearance of changing in every instance, but that is because there is only one variable.
Static class variables live as long as the class definition is loaded. This is usually until the VM exits. However, there are other ways a class can be unloaded. See, for example, this thread and this one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With