If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In Java, static members belong to the class rather than to individual instances (objects) of the class. They are shared among all instances of the class and can be accessed using the class name, without creating an object of the class. Static members are declared with the static
keyword.
There are two types of static members in Java:
Static Variables (Class Variables): Static variables are shared among all instances of the class. They are initialized only once when the class is loaded into memory and retain their value throughout the program's execution.
javaCopy code
public class MyClass {
// Static variable (class variable)
static int count = 0;
public MyClass() {
count++; // Increment count for each instance created
}
}
Static Methods (Class Methods): Static methods are also associated with the class and not with individual instances. They can be called using the class name and do not require an object to be created.
javaCopy code
public class MathUtility {
// Static method (class method)
public static int add(int a, int b) {
return a + b;
}
}
Accessing Static Members: Static members can be accessed using the class name or through an instance of the class. However, it is recommended to access static members using the class name to make it clear that the member is shared among all instances.
javaCopy code
// Accessing static variable
int totalCount = MyClass.count;
// Accessing static method
int sum = MathUtility.add(5, 3);
When to Use Static Members:
Note:
Comments: 0