| Difference between Local and Instance variable in Java with example
First of all we will take Local variable. We can use local variable inside method, constructor or any block in classes. The main thing is that it has only local scope and cannot cross that scope means if we define in one block then scope is only that block same as happen with method. And one of the main benefits of using local variable is that other methods in the class cannot use or aware of the local variable define in the method. Below is the example of local variable
if(i>10)
{
string websitename="crackyourinterview.com";
}
in above code scope of string variable is only that if block.
Now comes to Instance variable. This variable is bounded to its object itself. We will declared this variable in the class. And these declare outside the method. And when any object of class will use they will create a copy of the variable. So once some one made change to that variable will not reflect in any other instance of that class and scope of that to particular instance only.
class student{
Public string studentName;
public in studentage;
}
Here both of the variable are instance variable any method in the class can use these 2 variables. | | |