Using Static variables to Count Instances in Java
Java Static Members: Exercise-1 with Solution
Static Variables:
Write a Java program to create a class called "Counter" with a static variable count. Implement a constructor that increments count every time an object is created. Print the value of count after creating several objects.
Sample Solution:
Java Code:
Counter.java
// Define the Counter class
public class Counter {
// Static variable to keep track of the count of instances
private static int count = 0;
// Constructor increments the static variable count
public Counter() {
count++;
}
// Static method to get the value of count
public static int getCount() {
return count;
}
// Main method to test the Counter class
public static void main(String[] args) {
// Create several Counter objects
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();
// Print the value of count
System.out.println("Count: " + Counter.getCount());
}
}
Output:
Count: 3
Explanation:
- Define the Counter class:
- The Counter class is defined using the class keyword.
- Static variable to keep track of the count of instances:
- A private static variable count is declared to keep track of the number of instances created.
- Constructor increments the static variable count:
- The constructor Counter() is defined to increment the count variable every time a new instance is created.
- Static method to get the value of count:
- A static method getCount() is defined to return the value of the static variable count.
- Main method to test the Counter class:
- The main method is defined to test the Counter class.
- Several Counter objects (c1, c2, c3) are created.
- The value of count is printed using the getCount() method.
Note on Java Static Members:
In the above exercise, the static members work by:
- Static Variable: The static variable count is shared among all instances of the Counter class. This means that every time a new Counter object is created, the same count variable is incremented.
- Constructor: The constructor is used to increment the static variable count whenever a new instance of the Counter class is created.
Java Code Editor:
Improve this sample solution and post your code through Disqus.
Java Static Members Previous: Java Static Members Exercises Home.
Java Static Members Next: Using Static Methods in Java: MathUtility Class Example.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/java-exercises/static_members/java-static-members-exercise-1.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics