Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Local Variable and Instance Variable

 
akshay dev
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hey,
i am bit confused about local and instance variable. I know what a variable is but i am little messed up in the concept
of instance variable.Could you please help me.
And please tell me the difference between them.
 
Stelian Galmati
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can check this link from oracle: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html
 
dennis deems
Ranch Hand
Posts: 808
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's a small illustration:

The Collection named stacks is an instance variable. Every instance of Library will have its own. It is accessible anywhere within the class, from any method, for the duration of the instance's lifetime.
The Comparator named shelver is a local variable. It exists only while the sort method has scope. It can not be accessed anywhere in the class outside the scope of this method. When the sort method completes execution, the comparator goes out of scope and will be garbage collected.
 
ujjawal rohra
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Simply saying, any variable which is declared inside a method(including body or definition) or any block(loop, if-else block, constructor) is a local variable. Local variables can be accessed only within the block in which they are declared and not outside it.
Instance variables are those which are declared outside any block but directly within the class.They can be accessed anywhere within the class and even outside the class. See below

In the above code, variables var and var1 are declared outside any block but within the class hence they are instance variables. While variables local1, local2, local3, local4 are declared inside constructor, a method and an if block respectively, hence they are local variables.

Further, the modifiers public, private, protected apply only to instance variables and not to local variables.

Conceptually, whenever you create an object of a class then each object has a copy of instance variables. This means that you can access instance variables of a class when you make an object of this class by using a dot operator(For ex. obj.var1) but you cannot access local variables directly.

Hope this helps.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic