Java – Local Variables

Local Variable:
1. Sometime to meet the temporary requirement of the programmer we can declare a variable inside a method or block or constructor such type of variable is called local variable or temporary variable or stack variable or automatic variables.

Watch here:

2. Local variable will be stored in stack memory.
3. Local variable will be created while executing the block in which we declared it. Once the block execution complete automatically local variable will be destroyed hence the scope of a local variable is the block in which we declared it.
4. It is not recommended to perform initialization for local variables inside logical blocks because there is no guaranty for the execution of these at runtime.
5. It is highly recommended to perform initialization for local variables at the time of declaration at least with default values.
6. The only applicable modifier for a local variable is final. By mistake, if we are trying to apply any other modifier then we will get compile time error.
7. If we are not declaring with any modifier then by default it is default but this rule is applicable only for instance and static variables but not for local variables.

Conclusion:
1. For instance and static variable, JVM will provide default values and we are not required to perform initialization explicitly but for local variables, JVM would not provide a default, compulsory we should perform explicitly before using that variable.
2. Instance and static variable can be accessed by multiple threads simultaneously and hence these do not thread safe but in the case of local variables for every thread separate copy will be created and hence local variables are thread-safe.
3. Every variable in java should either instance or static or local. Every variable in java should be either primitive or reference hence various possible combinations of variables in Java are
A. Instance-primitive
c. Instance-reference
d. static-primitive
e. static-reference
f. local-primitive
g. local-reference