Java Static Variables and Functions
In Java, static variables belong to the class rather than any individual object. They are shared across all instances.
Static functions (or methods) can be called without creating an instance of the class and usually operate on static variables.
Java में, static variables class के होते हैं, किसी भी specific object के नहीं। ये सभी objects के बीच shared होते हैं।
Static functions को class का object बनाए बिना बुलाया जा सकता है और ये आमतौर पर static variables पर काम करते हैं।
Advantages of static members:
- Memory efficient — only one copy shared by all objects.
- Useful for constants or shared data.
- Utility/helper functions can be static.
- यादाश्त की बचत — एक ही copy सब objects के लिए shared।
- Constants या shared data के लिए उपयोगी।
- Utility या helper functions static हो सकते हैं।
Example 1: Static Variable in Employee Class
class Employee {
String name;
int age;
static int employeeCount = 0; // static variable
Employee(String name, int age) {
this.name = name;
this.age = age;
employeeCount++; // increment static count
}
}
public class Test {
public static void main(String[] args) {
Employee e1 = new Employee("Alice", 30);
Employee e2 = new Employee("Bob", 25);
System.out.println("Total employees: " + Employee.employeeCount);
}
}
Output:
Total employees: 2
Static variable employeeCount keeps track of how many Employee objects were created, shared by all instances.
Static variable employeeCount यह बताता है कि कितने Employee objects बनाए गए हैं, जो सभी objects के बीच shared होता है।
Example 2: Static Function in Employee Class
class Employee {
String name;
int age;
static int employeeCount = 0;
Employee(String name, int age) {
this.name = name;
this.age = age;
employeeCount++;
}
static void displayCount() { // static method
System.out.println("Employee count: " + employeeCount);
}
}
public class Test {
public static void main(String[] args) {
Employee e1 = new Employee("Alice", 30);
Employee e2 = new Employee("Bob", 25);
Employee.displayCount(); // call static method without object
}
}
Output:
Employee count: 2
Static method displayCount() prints the static employeeCount variable without needing an object instance.
Static method displayCount() static employeeCount variable को बिना object के कॉल करके print करता है।