in Java, Explain static variables with examples and a diagram.
In Java, a static variable is a class-level variable that is shared among all instances of that class. This means that there is only one copy of the static variable, regardless of how many objects of the class are created. Static variables are declared using the static
keyword.
Here’s a simple example to illustrate the concept of static variables:
class Counter {
// Static variable to keep track of the number of instances
static int count = 0;
// Constructor
Counter() {
count++; // Increment the count each time a new instance is created
}
// Static method to get the current count
static int getCount() {
return count;
}
}
public class Main {
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();
// Accessing the static variable using the class name
System.out.println("Total instances created: " + Counter.getCount());
}
}
Counter
class has a static variable count
that keeps track of how many instances of the class have been created.Counter
object is instantiated, the constructor increments the count
variable.getCount()
returns the current value of count
.Main
class, three instances of Counter
are created, and the total number of instances is printed using the static method.Here’s a simple diagram to represent the concept of static variables:
+-------------------+
| Counter |
+-------------------+
| - count: int | <--- Static Variable (Shared)
+-------------------+
| + Counter() | <--- Constructor
| + getCount(): int | <--- Static Method
+-------------------+
Instances:
+---------+ +---------+ +---------+
| c1 | | c2 | | c3 |
+---------+ +---------+ +---------+
| (refers to the same static variable) |
+-----------------------------------------+
count
is shared among all instances (c1
, c2
, c3
).count
in one instance affects all instances since they all refer to the same variable.