How do I create a static local variable in Java?

gameover picture gameover · Jan 17, 2010 · Viewed 85.5k times · Source

I've read Java does not support static local variables unlike C/C++. Now if I want to code a function with a local variable, whose value should persist between function calls, how do I do that?
Should I resort to using instance variables?

Answer

Ellie P. picture Ellie P. · Jan 17, 2010

You can have a static class variable, which will be preserved across all instances of the class. If that's what you want. If not, use an instance variable, which will only be preserved across method calls on this object.

public class Foo {
   static int bar;
   //set bar somewhere

   public int baz() {
      return 3 * bar;
   }
}