Open In App

Difference between Instance Variable and Local Variable

A variable is a name given to a memory location. It is the basic unit of storage in a program.

Instance Variable: These variables are declared within a class but outside a method, constructor, or block and always get a default value.



Example:

class Taxes  
{
int count; // Count is an Instance variable
/*...*/
}

Local Variable: These variables are declared within a method but do not get any default value.



Example:

int area()      
{
int length = 10; // Local variable
int breadth = 5; // Local variable
int rectarea = length*breadth; // Local variable
return rectarea;
}

Tabular difference between the instance variable vs local variable:

Instance Variable 

Local Variable 

They are defined in class but outside the body of methods.   They are defined as a type of variable declared within programming blocks or subroutines. 
These variables are created when an object is instantiated and are accessible to all constructors, methods, or blocks in class.  These variables are created when a block, method or constructor is started and the variable will be destroyed once it exits the block, method, or constructor.
These variables are destroyed when the object is destroyed.   These variables are destroyed when the constructor or method is exited.
It can be accessed throughout the class.   Its access is limited to the method in which it is declared.
They are used to reserving memory for data that the class needs and that too for the lifetime of the object. They are used to decreasing dependencies between components I.e., the complexity of code is decreased.
These variables are given a default value if it is not assigned by code.        These variables do not always have some value, so there must be a value assigned by code.
It is not compulsory to initialize instance variables before use.   It is important to initialize local variables before use.
It includes access modifiers such as private, public, protected, etc.   It does not include any access modifiers such as private, public, protected, etc.
Article Tags :