Variables and Memory Optimization

When you start coding, you need to be mindful to memory usage and leakage.

 If you are able to use local variable, then do it. This means that the variable will be used locally within a method, construct, or a block.  The lifetime of the variable is bounded by that construct, block, or method.

If you believe that variable is an attribute of a class instance, then declare it as a class attribute/variable.  In this case, every time you create an instance of that class, the variable will be located in heap memory and a slot will be allocated to it.  However, if you discover after a while that the class variable is not used across different methods and not needed to represent class instance state, then it is better to move it to the method where it was used

Class instances sometimes share some static variables that need to be kept among these instances.  This usage is mostly for static fixed values.  However, there may be some static variables used as shared resources.  In this case you need to synchronize the use of these resources to avoid race conditions.

Please check this example

public class Example {
   int myInstanceVar = 10;
   static int myStaticVar = 50;
   
   public static void main(String args[]){
      String myLocalVar = "100";
      Example obj = new Example();
      
      System.out.println("myInstanceVar = "+obj.myInstanceVar);
      System.out.println("myStaticVar =  "+Example.myStaticVar);
      System.out.println("myLocalVar = "+ myLocalVar);
   }
}
myLocalVar is initialized and destroyed once the execution of the method completes.  This is a very simple example, but in more complex examples, there would be may methods.
myInstanceVar is initialized and allocated to heap memory once object is constructed.
myStaticVar is allocated memory once program starts.

Document Actions