What is the difference between a local variable and an instance variable?

DWQA QuestionsCategory: JavaWhat is the difference between a local variable and an instance variable?
Editor Staff asked 1 month ago

What is the difference between a local variable and an instance variable?

1 Answers
Editor Staff answered 1 month ago

In Java, a local variable is typically used inside a method, constructor, or a block and has only local scope. Thus, this variable can be used only within the scope of a block. The best benefit of having a local variable is that other methods in the class won’t be even aware of that variable.
Example
1
2
3
4
if(x > 100)
{
String test = “Edureka”;
}
Whereas, an instance variable in Java, is a variable which is bounded to its object itself. These variables are declared within a class, but outside a method. Every object of that class will create it’s own copy of the variable while using it. Thus, any changes made to the variable won’t reflect in any other instances of that class and will be bound to that particular instance only.
1
2
3
4
class Test{
public String EmpName;
public int empAge;
}