This should be quite easy right? I am writing a program that allows users update an integer value using input.nextInt () , but the life span of that variable terminates with the end of the program, is there a way to permanently save the variable so I can use it the next time I run the program? Here's a scenario ,, user gets prompted to enter a value through input.nextInt (), and he enters 68 stored in num1, the next time I run the program I want to start with num1 having the value of 68(what the user previously entered), is this possible? And how?
-
1You need to write to a file: http://stackoverflow.com/questions/2885173/how-to-create-a-file-and-write-to-a-file-in-java ; and then read it: http://java67.blogspot.com/2012/11/how-to-read-file-in-java-using-scanner-example.html – AMACB Jan 24 '16 at 16:17
5 Answers
All objects used by the program are destroyed when the program ends. You must write that value in an external file such as a text file or a database, then read if when program starts again.

- 6,021
- 11
- 48
- 71
Program are running on the computer RAM. if you want to save data you have to write it to disk it's depend on your environment what is the right way to do that (database, file etc)

- 1,316
- 1
- 10
- 13
The value of num1 must be persisted to a data store such as a config file or database. After your user enters a value through input.nextInt(), this value should be captured and persisted to the data store. When your application is launched again, it should retrieve the value of num1 from the data store and assign it to this variable.

- 185
- 1
- 11
Everything is destroyed after System.exit(); is called. so you will need to save initial values of anything you want to save, externally. for that you can look into for example. Java file streaming such as: Object serialization.

- 31
- 1
- 5
Like others have said, your application runs in memory, and when it terminates the memory is cleaned and the data is lost.
What you are looking to do is called 'persisting' the data, and there are many ways in which you can do this. As mentioned you can use things like files and databases to do this.
Dependent on your application and the data you are looking to store, you might need to use systems of differing complexity - for example if you are making a game other people will run, you need to ensure it is stored somewhere it won't be touched, such as with your other game files. But if you are just looking to store data for an application you will run by yourself, you can simply write the data to a file anywhere, and then read it again at the beginning of your application.

- 810
- 6
- 21