tags:

views:

97

answers:

5

Possible Duplicate:
How do I create a static local variable in Java?

Hi I am noob to java I wanna access local variable of a function in another function. But java does java support static variable in a function? If not then how to access that variable.I do not want to make that local variable as instance variable of calss.

Thanks

+1  A: 

In the declaration of your method where you need to access the variable, include it as a parameter.

public int myMethod(int i){
    System.out.println(i);
}

And then pass the variable to that method as a parameter.

public static void main(String [] args){
    int myInt = 5;
    myMethod(myInt);
}
cheesysam
This way, one can get to the "contents" of the variable, not the variable itself. One cannot, for example, assign a new value to it.
Thilo
A: 

It depends but there are a few ways.

If you're in the same object you could use a normal member variable, if you're calling between objects you could just provide getters and setters for that variable. Alternately if the two methods are related just provide the value as a parameter.

When you talk about between one function and another function it's not clear whether you mean methods in the same class or between different classes. Maybe if you're thinking about functions in Java and not thinking about classes, objects and methods, you would find it useful to go over the basic object orientation stuff as well. I know I had that problem often when I was making the transition from procedural to object-oriented programming. It's a while ago now, but this series of tutorials helped me a lot with that.

glenatron
A: 

No you cannot declare a static variable in a method in java.

and you can not access a variable from one method in another method. rather if it is an object you can send its reference to other method through a method call. and if its a primitive then you can send its value.

GK
+1  A: 
  1. In Java you say "method" instead of "function".

  2. What do you mean by "static variable in a function"? If you mean C/C++ style static local variable, then you have to use class or instance variable, depending on your needs.

  3. "Local" means that something cannot be accessed outside it's scope. So you can't access method's local variable from outside of the method body, just by definition.

  4. And why can't you use class or instance variable?

witzar
do you mean class (static) or instance field?
WildWezyr
A: 

Maybe I'm totally wrong but the task sounds to me like a part of closures concept (even if authod didn't mean anything related).

So, java way is:

public void foo () {
   final SomeClass obj = new SomeClass ();
   Bar b = new Bar () {
      public void bar () {
         obj.doSmth ();
      }
   };
}

Of course, this concrete code is just an unuseful example.

John Doe