Dynamically scoped variable in java ? (a.k.a one variable per method execution)
I would like to know if it's possible in 开发者_StackOverflowjava to declare a variable local to the execution of the method.
For instance, if i'm doing some recursive stuff and i want to keep various counters specific to one particular execution of the method.
I don't know the correct english expression for that...
void method()
{
int i = 0; // this int is local to 'method'
}
This is how Java works by default. For example, in the following method:
void recursive(int i) {
int localI = 6;
i-= 1;
if (i > 0) {
recursive(i);
}
localI will stay local to the current execution of the method.
A normal, local variable inside a method is exactly what you mean. Those local variables are allocated on the stack. Each time you call the method, whether it's in a recursive manner or not, a new copy of the variable is created.
I think you might be talking about static
variables.
if you declare a static variable it will save it's value between executions of the methods.
精彩评论