Types of Variables

Java Programming language defines mainly three kind of variables.

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

    Instance variables in Java

    Instance variables are variables that are declare inside a class but outside any method,constructor or block. Instance variable are also variable of object commonly known as field or property. They are referred as object variable. Each object has its own copy of each variable and thus, it doesn’t effect the instance variable if one object changes the value of the variable.

    class Student
    {
        String name;
        int age;
    }

    Here name and age are instance variable of Student class.

    Static variables in Java

    Static are class variables declared with static keyword. Static variables are initialized only once. Static variables are also used in declaring constant along with final keyword.

    class Student
    {
        String name;
        int age;
        static int instituteCode=1101;
    }

    Here instituteCode is a static variable. Each object of Student class will share instituteCode property. 

    Local variables in Java

    Local variables are declared in method, constructor or block. Local variables are initialized when method, constructor or block start and will be destroyed once its end. Local variable reside in stack. Access modifiers are not used for local variable.

    float getDiscount(int price)
    {
     float discount;
     discount=price*(20/100);
     return discount;
    }

    Here discount is a local variable.