Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you get the previous value of a variable in Java?

Tags:

java

variables

Say way have a variable (let's say String Str) and the value of Str starts of as " " then as some code is running it is set to "test" then somewhere else in the code it is changed again to say "tester". Now in the program I want to find out what the previous value of Str was. Is this possible in Java?

So I am saying that the variable gets changed twice, and you want to find out what Str was before it got changed for the second time. So in the example above the latest value of Str would be "tester" but I wanted to find out what Str was before this (assuming you had no idea what it was before it was changed to tester) in this case I would want to be able to find out that Str was "test".

Is it at all possible to do this in Java?

like image 216
The Special One Avatar asked Mar 04 '09 15:03

The Special One


2 Answers

No, it's not possible, you have to save the previous value before you change it to do what you're asking for.

like image 162
Stefan Thyberg Avatar answered Sep 17 '22 15:09

Stefan Thyberg


Not as a native part of the language, no. You could write a setter that saved the current (previous?) value when the String changes, though.

private String str;
private String prev;

setStr(String s)
{
    prev = str;
    str = s;
}

Then just write a separate getter for prev.

Of course, this solution relies on you always using the setter to change the value of str.

Also, as deworde points out, if your program doesn't need this information, then you shouldn't modify your program to save it. If you need the information for debugging purposes you can just set a watch in your IDE's debugger.

like image 28
Bill the Lizard Avatar answered Sep 20 '22 15:09

Bill the Lizard