Java variable types

   

The Java programming language defines the following kinds of variables:

  1. Instance Variables
  2. Static Variables
  3. Local Variables

Instance Variables (Non-Static Fields)

  1. Non-Static Variables are called as Instance Variable.
  2. Instance variables are variables within a class but outside any method.
  3. Whenever we create an object of class then we can have certain attributes of the class that are unique for each object , that attribute variable is called as “Instance Variable“.
  4. Individual states of objects is stored in  “non-static fields”. (instance variable).
  5. Non-static fields are also known as instance variables because their values are unique to each instance of a class (to each object, in other words).

Sample Example

Class Person
{
String name;
int    age;
String gender;
};

Person P1,P2,P3;

In the above example we have created class “Person”. We can have different Attributes of Class Person such as name,age,gender . These attributes are unique for different objects. Such as for object P1′s name can be different from P2′s name. Such variables that are unique for individual object is called Instance Variable.

Class Variables (Static Fields)

  1. A class variable is any field declared with the static modifier.
  2. Exactly one copy of static or class variable is created , regardless of how many times the class has been instantiated.
  3. Suppose we have created 5 objects then all of the objects can share same variable.

Example :

Class Person
{
String name;
int    age;
String gender;

static String city = "Pune";
};

Person P1,P2,P3;

Static Variable In Java

Local Variables

  1. In order to store Temporary state we use local variables.
  2. Generally local variables are declared in the methods,constructors,blocks.
  3. “count” is local variable in following code snippet.
  4. Destroyed when method gets executed completely.

Example :

int counting(int n1,int n2)
  {
  int count;
  count = n1 + n2;
  return(count);
  }