devxlogo

Using Static Variables to Store State Across Instantiations

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 {2. 3. private static boolean myStaticFlag_ = false;4. 5.     public boolean  getFlag () {6.       return myStaticFlag_;7.   }8. 9.   public void  setFlag (boolean myStaticFlag) {10.     myStaticFlag_ = myStaticFlag;11.   }12. 13.   public static void main (String[] args) {14. 15.     TestFlag tf1 = new TestFlag();16.     System.out.println("1::tf1.myStaticFlag_ = " +  tf1.getFlag());17.     tf1.setFlag(true);18. 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:

 1::tf1.myStaticFlag=false2::tf2.myStaticFlag=true3::tf3.myStaticFlag=true

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.”

See also  lenso.ai - an AI reverse image search platform
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist