Static Variables in Java
beginner· OOP · Classes & Objects
Problem
A static variable belongs to the class itself rather than to any one object, so every object shares that exact same field — changing it through one object changes what every other object sees too.
Track how many Student objects have been created using a static counter, incremented once per object.
Input
3 Student objects created
Output
Total students created: 3
Java Program
Java
class Student {
static int totalStudents = 0;
Student() {
totalStudents++; // shared across every Student object, not per-instance
}
}
public class StaticVariables {
public static void main(String[] args) {
new Student();
new Student();
new Student();
System.out.println("Total students created: " + Student.totalStudents);
}
}Output
Total students created: 3
Core Logic
Incrementing a static counter inside the constructor, once per object created, tallies the total across every object without any object needing its own copy of that count.
How It Works
- 1
static int totalStudents = 0;declares a field that belongs to theStudentclass itself, not to any individual object. - 2The constructor
Student()runstotalStudents++;every time a new object is created, regardless of which object it is. - 3Because
totalStudentsis static, all three objects created here increment the exact same field, not three separate copies. - 4Reading
Student.totalStudentsafter creating three objects reports3, the running total.
Creating three
Student objects runs the constructor three times, so totalStudents ends at 3 — printed as "Total students created: 3".💡
Key Point: If totalStudents were an instance variable instead of static, each object would start its own copy back at 0, and there'd be no single shared count to report.
Key Concepts
static variableshared stateconstructor