I was giving example of local variable in java through below code .
class Sum
{
int a=7,b=3;//instance variable
public void add()
{
int c;//local variable
c=a+b;
System.out.println(c);
}
public static void main()
{
Sum obj = new Sum();
obj.add();
}
}
But while explaining code someone asked me, in above code you can declare variable c
as instance variable also as you declared a
and b
variable.
I didn't have an answer at that time. Can anyone explain to me what the benefit of using local variable in java?