You are here: Home / Topics / Explain the difference between instance variable and a class variable

Explain the difference between instance variable and a class variable

Filed under: Java Interview Questions on 2024-10-25 15:27:59

Instance variables and class variables (also known as static variables) are two types of variables in Java, and they have distinct characteristics and purposes. Here’s a detailed comparison:

Instance Variables

Definition: Instance variables are non-static variables defined within a class but outside any method. They are unique to each instance (object) of the class.

Memory Allocation: Each instance of the class has its own copy of instance variables, which are stored in the heap memory along with the object.

Scope: They can be accessed by all methods within the class and are specific to the object.

Default Values: Instance variables have default values (e.g., 0 for numeric types, false for boolean, null for object references) when an object is created.

Usage: They represent the state or attributes of an object. Each object can have different values for these variables.

Example:

class Car {
   String color; // Instance variable

   void displayColor() {
       System.out.println(color);
   }
}
 

 

Class Variables

Definition: Class variables are declared with the static keyword within a class. They are shared among all instances of the class.

Memory Allocation: Class variables are allocated memory once when the class is loaded, and there is only one copy for the entire class, regardless of how many objects are created.

Scope: They can be accessed directly using the class name or through instances of the class, but typically accessed using the class name for clarity.

Default Values: Like instance variables, class variables also have default values based on their data type.

Usage: They represent shared data or properties that are common to all instances. They can be used for counting instances, sharing constants, etc.

Example:

 

class Car {
   static int count = 0; // Class variable

   Car() {
       count++; // Increment the class variable when a new object is created
   }

   static void displayCount() {
       System.out.println("Number of cars: " + count);
   }
}
 

 

Summary of Differences

FeatureInstance VariableClass Variable
DeclarationNot staticStatic
Memory AllocationUnique for each instanceShared among all instances
ScopeInstance-specificClass-wide
Default ValuesYes (type-specific)Yes (type-specific)
AccessThrough object referencesThrough class name or instance
PurposeRepresents object state/attributesRepresents shared class properties

Understanding these differences helps in designing classes effectively and utilizing the correct type of variable based on the requirements of your program.

About Author:
J
Java     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.