Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The short answer: <code>static</code> variables only persist within a single JVM run, so after your first execution exits the fact that <code>CPT</code> was set to 100 is effectively lost. See <a href="http://java.sun.com/docs/books/tutorial/java/javaOO/classvars.html" rel="noreferrer">http://java.sun.com/docs/books/tutorial/java/javaOO/classvars.html</a> for a primer on static vs. non-static variables. Succintly, the only difference is that static variables are shared by all instances of a class - otherwise, they basically behave identically.</p> <p>The long(er) answer is that static variables are kind of like instance variables but for the <code>Class</code> object for your class. When the JVM exits, all the classes are unloaded and so the static variables no longer exist just like any instances of the class no longer exist. When you restart Java for the second run, it rereads the definition of your classes from your (compiled) source files, and sets <code>CPT</code> to zero just as you asked it to.</p> <p>(And in the situation you mentioned, running two JVMs at once leads to two <code>ClassLoaders</code> and two distinct <code>Class</code> objects, one per JVM, so they each have their own versions of the static variable.)</p> <p>If you want to persist any information between Java executions, you'll need to store it somewhere external (e.g. a file or database), and load this information on startup. If you want to share information between running Java processes, you'll need to have them communicate with each other to share this information (e.g. over TCP connections). This is true regardless of whether the variables in question are static or not.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload