62

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?

5
  • this is why Java needs closures (kidding).
    – D.C.
    Jan 17, 2010 at 4:01
  • @darren : What do closures have to do with static locals? Jan 17, 2010 at 4:47
  • 13
    he wanted static locals (in a C sense) to maintain state through multiple function calls. In other words having locals exist after the function returns. This is one use of closures.
    – D.C.
    Jan 17, 2010 at 5:21
  • 2
    TL;DR answer: you can't. Make a static member variable of the containing class.
    – Andrew
    May 19, 2017 at 14:09
  • Part of the confusion on this thread is that the "static" keyword works differently in C and Java. In C, if used inside a function, the state of that variable is preserved from one call to the next, but only has scope inside that function. Java doesn't have an equivalent keyword, but some answers correctly describe how you can use an object to emulate this behavior.
    – Dan H
    Aug 16, 2018 at 20:31

8 Answers 8

40

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;
   }
} 
5
  • 9
    I think in most of the cases instance variables should be just fine, if what @gameover want is something to replace method static local variables.
    – bryantsai
    Jan 17, 2010 at 3:40
  • I agree. It's pretty rare to want a non-final static variable. Assigning ID numbers to objects is an example, though--store the last used ID number as a static variable. assignID() returns lastID+1
    – Ellie P.
    Jan 17, 2010 at 3:51
  • 5
    @EllieP. return lastID++;
    – Cruncher
    Sep 16, 2013 at 15:26
  • To prevent confusion, you may want to restrict yourself to using static variables for static methods, and instance variables for instance methods. For instance methods with static functionality, encapsulate that functionality in a static method which is called from the instance method.
    – augurar
    Jul 7, 2014 at 18:14
  • it gives error in ideone error: illegal start of expression Mar 4, 2015 at 12:27
8

If you want to reuse variable value between function calls and isolate this variable from other methods, you should encapsulate it in an object. First, define a class with only the "static-like" variables and the function you need:

class MyFunctionWithState {
    private int myVar = 0;
    public int call() {
      myVar++;
      return myVar;
    }
 }

Then, from your client code:

class Foo {
    private MyFunctionWithState func = new MyFunctionWithState();
    public int bar() {
      return func.call();
    }
 }

Now if func relies on the internal state of Foo you can either pass the relevant data through call() or pass an instance of Foo and let the function call the appropriate getters:

class MyFunctionWithState {
    private int myVar = 0;
    public int call( Foo f ) {
      myVar += f.getBaz();
      return myVar;
    }
 }

class Foo {
    private MyFunctionWithState func = new MyFunctionWithState();
    public int bar() {
      return func.call( this );
    }
    public int getBaz() {  /*...*/  }
 }
2
  • 1
    Why does it have to be so complicated? Does placing static int myVar in a member function conflict with some part of the java language or feature? I do not agree that it's rare to want something of this type either. Maybe I need some function to keep to the state of a variable and I don't want all other functions within the class to have access to that variable. It's much better to have the variable closer to where it is used. I guess I could place the variable right above the function, but that still allows causes confusion when other functions might be using the same variable name. Aug 27, 2015 at 15:32
  • When I said " Does placing static int myVar in a member function conflict with some part of the java language or feature?", I meant "would it possible to add this language feature in a future java version?" Aug 27, 2015 at 15:37
5

Local Variables are variables inside a method. Only method gets to access these variables. you cannot have a static local variable , but you can use instance variables or class variables.

If you have your method as static which by default creates a copy of this method to all the objects and cant be broken down any further as local variables limit their access only to the method in which they reside.

4

Should I resort to using instance variables?

yes - after all, that is what instance variables are for. They store the state between invocations of the methods of the object. Having static class variables can sort of achieve the same result, but can make your program more coupled and harder to test/mock/maintain.

2

Disclaimer: Just because you can, doesn't mean you should

Although Java doesn't support static local variables, it's fairly easy to emulate in recent versions of Java. From Java 16 onwards, it is possible to create a local class with a mutable static field in a method. Subsequently, you mutate the local class's static field just like you would in C/C++.

public class Main {

    public void foo() {
        class Local {
            static int count = 0;
        }
        Local.count++;
    }
    
}

Before Java 16, local classes may only contain static constants.

1

In the following example count behaves like a static local variable, that you might use in C:

public class Foo {

   private int count = 0;

   public int getCount() {
       return count++;               
   }
} 

There are no static local variables like other languages support. Since java is very "class"-oriented, it tries to bring it to that context. If you want to simulate that behavior, you use an instance variable, which is only used by this method. So this is static for different method calls, not for the class itself.

2
  • 1
    Static for a single instance does not sound very static to me. The main point of static is A) global value in the class. Does no depend on the instance. B) Avoid creating a variable for every instance :)
    – borjab
    Sep 23, 2015 at 11:34
  • @borjab: True, but since the OP wrote: Now if I want to code a function with a local variable, whose value should persist between function calls, how do I do that? ... it seemed right to respond with the obvious. Static depends somewhat on the context: For the function within this instance it would be static ... on the other hand regular static classes aren't very static amongst different instances of the program or even different devices ;-)
    – Levite
    Sep 23, 2015 at 12:22
0

Either you marked an answer correct that wasn't, or you actually wanted static class variables - but the right answer is basically Levit's, or technically a mixture of all the answers.

For people from a C background like me, truly wanting static function-local variables purely for the scope advantage over globals, it seems the answer is you can't in Java. Not without doing something like @paradigmatic is going for with an instance of a class with a static global and getter() unique to the instance of the class you are running your function in.

If, as I suspect, you're running the class as a Singleton, or completely statically like the inately procedural programmer we all started as, @Ellie P's or @user2626445's answer would work fine since no other instance is going to screw up your global. But to achieve what I think it is you want it should actually be just an instance variable, which is a global in C. They persist across function calls but allow your function to be used in an OO way, so multiple instances can keep their own persistent variables for this particular function.

Personally, I get around this in jave the same way I get around Hi-Tech C not allowing function bit variables, by declaring the global in the file just above the function declaration. That way me when I hack the code later is less likely to think it's a global and be tempted to mess with it - isn't that why we encapsulate things?

-3

final int intVar = 1; // Will be inited only once. Behaves as C++ static local var in the method.

2
  • 4
    This is a misleading answer, since the only reason intVar behaves like a C++ static local variable in this example is because it's assigned a constant. e.g. in void method(int arg) { final int intVar = arg; ... }, intVar will not behave like a C++ static local variable.
    – Max Nanasy
    Sep 5, 2014 at 21:50
  • 1
    you can't increment or decrement final variables Jan 27, 2015 at 14:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.