Local variable is also called as stack variable/temporary variable.
Local Variables will be created while executing the block in which we declared it.
Once block execution completes automatically local variable will be destroyed hence the scope of local variable is the block in which we declared it.
Local variable is defined in method/block/constructor.
For local variable we need to initialize with value compulsory.Because Jvm wont provide default values.
class Test{
public static void main(String a[]){
int i=0;
for(int j=0;j<3;j++){
i=i+j;
}
System.out.println(j+””+i);//Compilation Error
}
}
class Test1{
public static void main(String a[]){
try{
int j=Integer.parseInt(“ten”);
}
catch(NumberFormatException e){
j=10; //Compilation Error
}
System.out.println(j);//Compilation Error
}
}
class Test2{
public static void main(String a[]){
int j;
System.out.println(“Hello”);
}
}//compiles fine
Before using that variable ie., if we are not using then it is not required to perform initialization.
class Test3{
public static void main(String a[]){
int j;
System.out.println(j);//Compilation Error
}
}
Before the usage of variable it has to be initialize.
class Test4{
public static void main(String a[]){
int i=0;
if(a.length>0){
i=10;
}
System.out.println(i);//Compilation Error variable i has not been initialised.
}
}
class Test5{
public static void main(String a[]){
int x;
if(a.length>0){
x=10;
}
else{
x=20;
}
System.out.println(x);//Compilation Error variable i has not been initialized.
}
}
java Test5 a b
o/p:10
java Test5
o/p: 20
Never recommended to initialize the local variable inside the block.Because there is no guarantee for execution these blocks always at run time.
It is highly recommended to initialize the local variable at least with default value.
eg:Connection con=DriverManager.getConnection….
The only applicable modifier for local variables is final.By mistake if any other modifier is applied then we get compile time error.

For instance and static variable Jvm will provide the default values and we are not required to perform values explicitly.But for local variables Jvm will not provide default values compulsory we have to provide values before using that variable.
Instance and static variables can be accessed by multiple threads simultaneously and hence these are not thread safe.
Where as in local variables for every thread a separate copy will be created and hence local variables are thread safe.
Every variable in java should be either instance or static or local.
Every variable in java should be with primitive or reference.Hence various possible combinations of variables in java are:
