Reputation: 23256
Let there be three classes named Tester_1
,Tester_2
,Tester_3
. They are defined as :
Tester_1:
class Tester_1 {
public static void main(String args[]) {
Tester_2.setBoolean(true);
System.out.println(Tester_2.getBoolean());
}
}
Tester_2:
class Tester_2 {
public static boolean var = false; // Static var
public static void setBoolean(boolean value) {
var = value;
}
public static boolean getBoolean() {
return var;
}
}
Tester_3:
class Tester_3 {
public static void main(String args[]) {
System.out.println(Tester_2.getBoolean());
}
}
After I compile all the three classes, I run them in the following order :
java Tester_1
java Tester_3
but I get this output :
true from the first run and false from the second run. Why is that ? When Tester_1 sets the boolean to a value true
why do I get the default false
when I run Tester_3 ?
Upvotes: 3
Views: 129
Reputation: 13872
java Tester_1
This is 1st run of program. (i.e. a process)
java Tester_3
This is 2nd run of program. (another process)
static
values persist within a process. not across processes.
Upvotes: 0
Reputation: 6855
Two separate executions --> different results.
JVM turns it more interesting as it erases previous data for every execution.
Upvotes: 0
Reputation: 21902
Because static variables hold their value staticly within the JVM, but is not held across JVMs. Once the JVM process exits, it's variable values in memory are destroyed. When the second JVM is started, then everything is reinitialized.
If you need to keep values across runs, you will have to persist them somewhere (to the file system or a database for example).
Upvotes: 1
Reputation: 328629
static
is only valid at the Java Virtual Machine (JVM) level.
Each time you call java xxx
you create a new JVM which does not share anything with the previous call => all static variables get their default value again.
Upvotes: 7