In this post, we will learn the difference between Static Variables and Instance variables in Java. This is a frequently asked question in Java interviews for beginners. Let's dive into it.
Feature | Static Variable | Instance Variable |
---|---|---|
Declaration | Declared using the static keyword. | Declared without the static keyword. |
Memory Allocation | Only one copy of the variable is created and shared by all instances of the class. | Each instance of the class has its own separate copy of the variable. |
Initialization | Initialized only once, when the class is loaded into memory. | Initialized separately for each instance of the class, when an object is created. |
Access | Can be accessed using the class name or instance reference. | Can be accessed only using an instance reference. |
Usage | Typically used for constants, configuration values, or shared data among objects. | Used for data that is unique to each instance of the class. |
When to Use | When the value of the variable is common for all objects of the class. | When each object needs its own distinct value for the variable. |
Lifetime | Lives as long as the class is loaded in memory. | Lives as long as the instance of the class exists. |
Example | static int count = 0; | int age; or String name; |
Static Variable Example:
Static variables belong to the class and are shared among all instances of the class. When the value of a static variable is changed, the change is reflected in all instances of the class.
class Employee {
static int totalEmployees = 0; // Static variable shared among all Employee instances
String name; // Instance variable
public Employee(String name) {
this.name = name;
totalEmployees++; // Increment the static variable whenever a new Employee is created
}
}
public class StaticVsInstanceVariable {
public static void main(String[] args) {
Employee emp1 = new Employee("John");
Employee emp2 = new Employee("Alice");
Employee emp3 = new Employee("Bob");
System.out.println("Total Employees: " + Employee.totalEmployees); // Output: Total Employees: 3
}
}
Output:
Total Employees: 3
Instance Variable Example:
Instance variables are specific to each instance of the class. Each object created from the class has its own copy of instance variables.
class Car {
String brand; // Instance variable
int year; // Instance variable
public Car(String brand, int year) {
this.brand = brand;
this.year = year;
}
public void displayDetails() {
System.out.println("Brand: " + brand + ", Year: " + year);
}
}
public class StaticVsInstanceVariable {
public static void main(String[] args) {
Car car1 = new Car("Toyota", 2022);
Car car2 = new Car("Honda", 2021);
car1.displayDetails(); // Output: Brand: Toyota, Year: 2022
car2.displayDetails(); // Output: Brand: Honda, Year: 2021
}
}
Output:
Brand: Toyota, Year: 2022
Brand: Honda, Year: 2021
Interview Questions
Java
X vs Y
Comments
Post a Comment