0

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?

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Manjeet Singh
  • 57
  • 1
  • 6
  • You should declare your variables for the scope in which they are needed (that includes their full lifecycle). If a variable is only needed in a single method then make it a local variable. – Joakim Danielson Jul 05 '20 at 09:36
  • Possibly related: [Java Instance Variables vs Local Variables](https://stackoverflow.com/q/1794141) – Pshemo Jul 05 '20 at 10:07
  • 1
    The benefits are that you don't pollute larger namespaces unnecessarily, or larger execution contexts either. Variables should be declared in the smallest possible enclosing scope. – user207421 Jul 05 '20 at 10:15

1 Answers1

3

You can certainly define c as an instance variable, but you should only do so if it makes sense.

Instance variables represent the state of an instance (i.e. the state of the object). Their values should be available as long as the instance exists.

Local variables are temporary in nature, and their value is no longer needed after the method in which they are declared returns.

Fewer instance variables in your classes will require less storage space, and will also make it easier to understand your code.

For example, if you changed c to be an instance variable, someone who tried to understand your code would have to search your entire class (and possibly sub-classes as well) to understand the meaning of changing the value of c (i.e. how it would affect other methods and sub-classes). When c is local, on the other hand, one only has to read the single method in which it appears in order to fully understand its purpose.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • @Eran please tell me what is the benefit of this keyword. i know The this keyword can be used to refer current class instance variable. but why we are taking same name of parameter and instance variable – Manjeet Singh Jul 05 '20 at 15:54