Variables in Java

A variable is a piece of memory location that contains a data value. Variables are used to store information which is needed to develop Java programs.

Types of variables

There are three types of variables available in Java.
1. Instance variable
2. Static variable
3. Local variable

Instance variable

  • Instance variable is also known as non-static variable. It has the unique value for each object (instance).
  • Instance variable is created when an object is created with new keyword and destroyed when object is destroyed.

Static variable

  • Static variable is the class level variable which is declared with static keyword.
  • Static variable tells the compiler that there is only one copy of this variable in existence.
  • Static variable is created when program starts and destroyed when the program stop.

Local variable

  • Local variable is declared inside the method, constructor and block.
  • There is no special keyword for declaring local variable.
  • Local variable can be accessed only inside the method, constructor and block.

Example: Simple program to understand the variable types

File Name: VariableType.java

class VariableType
{
     int a=10;          //instance variable
     static int b=20;          //static variable
     public int m1()
     {
          int c = 30;          //local variable
          System.out.println("c = "+c);
          return 0;
     }
     public static void main(String args[])
     {
          VariableType v = new VariableType ();
          System.out.println("a = "+v.a+"  b = "+b);
          v.m1();          //invoke the m1 method
     }
}


Output:
a = 1  b = 20
c = 30