0
0
Javaprogramming~15 mins

Static variables in Java - Mini Project: Build & Apply

Choose your learning style8 modes available
folder_codeUnderstanding Static Variables in Java
📖 Scenario: You are creating a simple program to track how many objects of a class have been created. This is useful in many real-world situations, like counting how many users have signed up or how many products are in stock.
🎯 Goal: Build a Java program that uses a static variable to count the number of instances created from a class called Counter. You will see how static variables keep a shared value for all objects.
📋 What You'll Learn
Create a class named Counter with a static variable count initialized to 0
Add a constructor in Counter that increases count by 1 each time an object is created
Create three objects of the Counter class
Print the value of the static variable count to show how many objects were created
💡 Why This Matters
🌍 Real World
Counting how many instances of a class exist is useful in resource management, like tracking active users or open connections.
💼 Career
Understanding static variables is important for Java developers to manage shared data and memory efficiently.
Progress0 / 4 steps
1
Create the Counter class with a static variable
Create a class called Counter with a static int count variable initialized to 0.
Java
💡 Need a hint?

Remember, static means the variable belongs to the class, not to any single object.

2
Add a constructor to increase the count
Add a constructor to the Counter class that increases the count variable by 1 each time a new object is created.
Java
💡 Need a hint?

The constructor has the same name as the class and no return type.

3
Create three Counter objects
In the main method, create three objects of the Counter class named c1, c2, and c3.
Java
💡 Need a hint?

Use the new keyword to create objects.

4
Print the total count of Counter objects
Add a System.out.println statement in the main method to print the value of Counter.count.
Java
💡 Need a hint?

Access the static variable using the class name, not the object.