0

does anyone know how to replace variable value after a program that changes it? I tried static variable before, but it doesn't save after you close the program.

For example

import java.lang.Math;

public class Main {

  static int A1;

  public static void main (String [] args) {

    A1=(int) (1+Math.random()*10); 
  }      
}

Let's say the first time the program is run, A1 holds a value of 5. Is it possible that next time the program is run, A1 still holds a value of 5 instead of zero? (before reaching the main method)

Thanks

z1lent
  • 147
  • 1
  • 1
  • 10
  • 2
    https://docs.oracle.com/javase/tutorial/essential/io/ – Reimeus Oct 01 '15 at 18:12
  • Or if the amount of data you want to save is small, look at the [Java Preferences API](http://stackoverflow.com/questions/10246503/java-how-do-you-use-the-preference-api-where-do-these-variables-store). – markspace Oct 01 '15 at 19:00

2 Answers2

4

Of course not, when the program exits the portion of memory it was using is freed for other programs. The only way to do it is writing to a file and restore the value from the file at the initialization of the program.

Dici
  • 25,226
  • 7
  • 41
  • 82
  • Writing to a file isn't the only way. There are other methods of persisting data. – GriffeyDog Oct 01 '15 at 18:27
  • @GriffeyDog like ? Any permanent resource is ultimately a file. If you're thinking of a DB or something like that, it's still a file (or several files). I could say it is the *best* way to do it because I don't believe the OP needs something more complicated than a mere file, but I think there is no ambiguity – Dici Oct 01 '15 at 18:36
0

The most easy to do that in Java is to use Preferences API, the most easy way to use it is

prefs = Preferences.userRoot().node(this.getClass().getName());
String ID = "A1";
if (prefs.getInt(ID, -1)
    prefs.putInt(ID, (int) (1+Math.random()*10));
A1 = prefs.getInt(ID, -1)

to get more info, juste Google "java preferences api"

A.N. O'Nyme
  • 141
  • 4