You are here: Home / Topics / Differentiate between instance and local variables.

Differentiate between instance and local variables.

Filed under: Java Interview Questions on 2024-10-25 14:42:18

Instance variables and local variables in Java have distinct characteristics and purposes:

Instance Variables

  • Definition: Instance variables are attributes defined in a class and are associated with instances (objects) of that class.
  • Scope: They can be accessed by all methods within the class.
  • Lifetime: Their lifetime is tied to the object; they are created when an object is instantiated and destroyed when the object is destroyed.
  • Default Values: Instance variables have default values (e.g., 0 for numeric types, false for boolean, null for object references).
  • Memory Location: They are stored in the heap memory as part of the object.

Example:

class Car {
   String color; // Instance variable

   void displayColor() {
       System.out.println(color); // Accessing instance variable
   }
}
 

 

Local Variables

  • Definition: Local variables are defined within a method, constructor, or block and are used to hold temporary data.
  • Scope: They can only be accessed within the method, constructor, or block where they are declared.
  • Lifetime: Their lifetime is limited to the execution of the method or block; they are created when the method is called and destroyed when it exits.
  • Default Values: Local variables do not have default values and must be initialized before use.
  • Memory Location: They are stored in the stack memory.

Example:

class Calculator {
   void add() {
       int sum = 0; // Local variable
       sum = 5 + 3;
       System.out.println(sum);
   }
}
 

 

Summary

  • Instance variables are tied to an object's state and can be accessed by all methods in the class, while local variables are temporary and confined to the method in which they are declared. Instance variables have default values, whereas local variables must be explicitly initialized.
About Author:
J
Java     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.