In Delphi / Pascal there is a mechanism by which local variables in a method can remember a value from one method call to the next. This is done using typed constants. For example:
procedure blah();
const
i: integer = 0;
begin
i := i + 1;
writeln(i);
end;
On each call to blah() i will increment. The output will look like:
1 2 3 4 5 ...
(each number on separate lines, but the editor here put them on the same line)
Is there an equivalent thing with Java?
you can use static variables. which are initiated once on the first call. and on each call they save the latest value.
public class usingBlah{
static int i = 0;
void blah() {
i++;
//print here by Log.i or whatever
}
}
here, like your code in delphi, i is defined on the first call and initiated. on the next calls it will save the latest value.
May be static variables can help you.
Static variables are initialized just one time when the first instance of the class is being created. After that it stores the value.
The closest equivalent in Java is a static variable of a class. That has static lifetime, but also has a wider scope than a Delphi assignable typed constant.
In Java there is nothing exactly like Delphi's rather quaintly named assignable typed constants that has local scope, but static lifetime. A static class variable is as close as you can get.
In C/C++ you could use a local variable with static storage duration, which has the same semantics as Delphi's assignable typed constants.
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