Variables and Memory Optimization
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); } }
Document Actions