views:

114

answers:

4

hi,

I would like to know if it's possible in java 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...

+6  A: 
void method()
{
     int i = 0;  // this int is local to 'method'
}
Ed Swangren
that has to be the easiest 50 rep you ever scored :)
skaffman
lol, yes. 65 actually :)
Ed Swangren
+5  A: 

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.

Mike Clark
Indent your code with four spaces to have it formatted as source code. I also added a missing `}` and corrected a wrong variable name in the declaration for you.
Jesper
Oops, the variable name in the declaration wasn't wrong.
Jesper
A: 

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.

Itsik
You mean `static` local variables as in C or C++. Something like that does not exist in Java.
Jesper
If you declare a static variable in the class the method is in, you can use the value between method calls. Something very useful for recursion. I'm trying to believe the person asking the question knows what a local variable is.
Itsik
It seems to me that he's asking the opposite of a static member variable; he wants a 'variable local to the execution of the method', i.e. a normal, local variable.
Jesper
+1  A: 

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.

Jesper