Variables

A variable is a named part of memory giving 3 information –
int a = 10;
1) A data type it can hold
2) The name of the variable
3) The value of the variable

The three types of variables are :

1] Class Variables : A variable defined outside all methods and whose scope is throughout the class is called Class Variable.  Class Variable takes a default value depending on its data type.
For calling methods of a class we should create an instance of that class.

In this example ‘x’ is a class variable. Name the file as ClassVariabl.java since it contains main().

class a                                Output :
{                                        0
   int x;                               0
   void met1()
   {  
       System.out.println(x);
   }
}
class ClassVariable
{
   public static void main(String args[])
   {
      a m=new a();
      m.met1();
      System.out.println(m.x);
   }
}

2] Method Variable : A variable defined inside a method and whose scope is only within that method is called Method Variable.

Method Variable needs to be mandetarilly initialized.

class MethodVariable                        Output :
{                                                       10
    void met1()
    {
        int x=10;
        System.out.println(x);
    }
    public static void main(String args[])
    {
        MethodVariable p = new MethodVariable();
        p.met1();
    }
}

3] Instance Variable : Static Variables have only one memory location and all instances share the same where as non-static variables can take separate values for different instances.

All non-static Class Variables are called Instance Variables.
class InstanceVariable                        Output :
{                                                        60
    static int x = 10;                             20
    int y = 20;
    public static void main(String args[])
    {
        InstanceVariable i = new InstanceVariable();
        i.x = 40;
        i.y = 100;
        InstanceVariable j = new InstanceVariable();
        j.x = 60;
        j.y = 200;
        InstanceVariable k = new InstanceVariable();
        System.out.println(k.x);
        System.out.println(k.y);
    }
}