Static Variable Example
This program demonstrates static variable usage.
Problem Statement
Write a Java program to use static variable count in Student class to track number of objects created.
Source Code
| 1 | class Student { |
| 2 | static int count=0; |
| 3 | Student(){ count++; } |
| 4 | } |
| 5 | public class StaticVariable { |
| 6 | public static void main(String[] args) { |
| 7 | System.out.println("Eduinq Static Variable"); |
| 8 | Student s1=new Student(); |
| 9 | Student s2=new Student(); |
| 10 | Student s3=new Student(); |
| 11 | System.out.println("Number of Student objects created: "+Student.count); |
| 12 | } |
| 13 | } |
Program Output
Eduinq Static Variable Number of Student objects created: 3
Explanation
A static variable belongs to the class, not individual objects. - Each time a new object is created, constructor increments count. - Since count is static, all objects share the same variable, ensuring a cumulative total. - This demonstrates how static variables can be used to track class level information rather than object specific data. Conclusion: Shows how to use static variable to track object count.