3

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 ?

Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328

4 Answers4

7

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.

assylias
  • 321,522
  • 82
  • 660
  • 783
  • Is there any way I can _bind_ the new process, `java Tester_3` here with the existing JVM ? – Suhail Gupta Jan 07 '13 at 13:06
  • 1
    I don't think you can - but you can always call `Tester_3.main()` from the first program. You could maybe explain in more details what you are trying to achieve. – assylias Jan 07 '13 at 13:08
1

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).

mprivat
  • 21,582
  • 4
  • 54
  • 64
  • Else than file system or database,isn't there _any_ other way to persist the values ? – Suhail Gupta Jan 07 '13 at 13:04
  • There are plenty of ways, but if you think file system or database is too hard already, you're in for a shock. Depending on the complexity of what you are trying to store, stick with file system if it's simple data (like a boolean). Read about serialization and externalization. http://stackoverflow.com/questions/817853/what-is-the-difference-between-serializable-and-externalizable-in-java – mprivat Jan 07 '13 at 13:06
0

Two separate executions --> different results.

JVM turns it more interesting as it erases previous data for every execution.

Vinay Veluri
  • 6,671
  • 5
  • 32
  • 56
0

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.

Azodious
  • 13,752
  • 1
  • 36
  • 71