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?
No, it's not possible, you have to save the previous value before you change it to do what you're asking for.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With