aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Local Variable and Instance Variable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Local Variable and Instance Variable" Watch "Local Variable and Instance Variable" New topic
Author

Local Variable and Instance Variable

akshay dev
Greenhorn

Joined: Nov 08, 2012
Posts: 19
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

Joined: Aug 12, 2010
Posts: 3
You can check this link from oracle: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html
dennis deems
Ranch Hand

Joined: Mar 12, 2011
Posts: 808
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

Joined: Mar 20, 2010
Posts: 105
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.


SCJP 6
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Local Variable and Instance Variable