Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Beginner
Feb 13, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Using Static Variables to Store State Across Instantiations

There are several situations when you need to retain the state of a flag between different instances in a program. The standard way to do this is to declare the flag static. The state of the flag will be maintained across multiple instantiations of the class. However, the static flag is maintained only as long the class is not reloaded. As a result, whenever you run the program afresh, the flag will lose its state.
1.   public class TestFlag {
3. private static boolean myStaticFlag_ = false;
5.     public boolean  getFlag () {
6.       return myStaticFlag_;
7.   }
9.   public void  setFlag (boolean myStaticFlag) {
10.     myStaticFlag_ = myStaticFlag;
11.   }
13.   public static void main (String[] args) {
15.     TestFlag tf1 = new TestFlag();
16.     System.out.println("1::tf1.myStaticFlag_ = " +  tf1.getFlag());
17.     tf1.setFlag(true);
19.     TestFlag tf2 = new TestFlag();
20.     System.out.println("2::tf1.myStaticFlag_ = " +  tf1.getFlag());
21.     System.out.println("3::tf2.myStaticFlag_ = " +  tf2.getFlag());
22.   }
23. }
Running this program gives you the following output:
The class TestFlag defines one private variable, myStaticFlag, and two methods to set it or query its state. Lines 15-16 instantiate a new object of type TestFlag and print out the state of the flag. The state is initially false since it was declared as such. Line 17 sets the state of the flag to true for object tf1. Line 19 constructs another object, tf2, of type TestFlag. Lines 21-22 print out the value of the flag for both tf1 and tf2. Note that the flag retains its state of true and does not get initialized to false because it is a class variable. Hence, both tf1.myStaticFlag and tf2.myStaticFlag refer to the same variable.

For a demonstration of how static flags are typically used, see the Tips: "Implementing the Singleton Pattern" and "A Mutable Singleton."

Ajit Sagar
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date