Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How long do my static variables live?

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?

like image 469
stwissel Avatar asked May 30 '13 02:05

stwissel


People also ask

Are static variables permanent?

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.

Do static variables keep their value?

A static variable continues to exist and retains its most recent value.

What is the lifetime of static variable in Java?

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.

Do static variables stay the same?

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.


1 Answers

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.

like image 60
Ted Hopp Avatar answered Oct 03 '22 09:10

Ted Hopp