Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a static local variable in Java?

Tags:

java

scope

static

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?

like image 989
gameover Avatar asked Jan 17 '10 03:01

gameover


People also ask

Can we create static local variable in Java?

In Java, a static variable is a class variable (for whole class). So if we have static local variable (a variable with scope limited to function), it violates the purpose of static. Hence compiler does not allow static local variable.

How do you create a local variable in Java?

Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor, or block. Access modifiers cannot be used for local variables. Local variables are visible only within the declared method, constructor, or block.


2 Answers

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;    } }  
like image 60
Ellie P. Avatar answered Sep 19 '22 18:09

Ellie P.


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() {  /*...*/  }  } 
like image 41
paradigmatic Avatar answered Sep 18 '22 18:09

paradigmatic