Sunday, August 24, 2008

Types of Variables...

Well it is important to know what are the types of variables because there behaviour and their life and death is directly related to their type! There are 6 types of variables and I classify them on basis of 2 things to make you understand better.

- Depending upon what a variable holds they are classified as
1. Primitive Variable
2. Reference Variable

- Depending upon where they are created they are classified as
1. Class variable ( also called static variables)
2. Instance variable
3. Method Parameter
4. Local Variable.

Let's go one by one to understand them. A primitive variable is one which holds the primitive e.g: an int, a char etc. A reference variable is one which holds an object of any class, it can be java API class like String or your wn created class. A class variable is one which is a static variable and inside the class definition. This variable is created when the class loads in the memory and stays there till the class is in the memory. A class variable is not attached to any instance of that class. A instance variable is a non-static member of which is attached to the specific instance of the class. It is reated when a class instance is created and stays in memory untill that instance is in the memory. A method parameter is one which we write in method definition to accept the method arguments the method call is passing to it. This thing will be clear after you see the following example. And lastly a local variable is the one which is declared inside a method body, it is also sometimes called method variable.

Lets take an example to show each type of variable and identify there types..
class City
{
static int name;
Lake l;
int road;
void getDistance(City c )
{
int distance;
}
}
Here,
distance is method variable,
c is method parameter,
road is instance variable,
l is reference variable,
name is class variable
I hope you got it now.. if not fire the doubts in comments! :)

1 comment:

Prem Sankar C said...

Dear ....

Are you interested in Writing an article 'introduction to java' for beginners ?

contact me imobino@gmail.com