Loading...
Java

Types Of Variables

Variables are divided into three types based on behavior and position of declaration. They are:
1. Instance Variables
2. Static Variables
3. Local Variables

  1. Instance Variables:
    –> Instance variables are the variables which values vary from object to object.
    –> They are created at the time of object creation with the help of a ‘new’ keyword and destroyed at the time of object destruction hence, the scope of instance variables is same as the scope of the object.
    –> For every object a separate copy of instance variable is created.
    –>They are stores on the heap as the part of object.
    –> Instance variable should be declared bin the class directly but out side of any method or block or constructor.
    –> They can be accessed directly from Instance area. But cannot be accessed by static area.
    –> But by using object reference we can access instance variable from static area.
    –> They are also known as object level variables or attributes.
  2. Static Variables:
    –> If the value of a variable is not varied from object to object then such type of variables are declared at class level by using static modifiers.
    –> In Static variables for entire class only one copy will be created and stared by every object of that class.
    –> Static variables are created at the time of class loading and destroyed at the time of class unloading hence, the scope of the static variable is exactly same as the scope of the .class file.
    –> Static variables will be stored in method area. They should be declared within the class directly but out of any method or block or constructor.
    –> They can be accessed from both instance and static and static areas directly.
    –> They can be accessed either by class name or by object reference but class name should be used.
    –> But within the same class we can access them directly with out class name.
    –> Static variables are also known as class level variables or fields.
  3. Local Variables:
    –> Local variables are temporary variables declared inside a method, block or constructor.
    –> They are also known as temporary variables, stack variables or automatic variables.
    –> They are stored in stored inside stack.
    –> Local variables are created as part of the block execution in which they are declared and destroyed once that block execution is completed.
    –> The scope of the local variables is same as the scope of the block in which it is created.
    –> For the local variables JVM won’t provide any default values we should initialize explicitly before using that variable.
    –> It is highly recommended to initialize the local variable at the time of declaration.


Leave a Reply

Your email address will not be published. Required fields are marked *