The static
keyword in Java is used for memory management primarily. It can be applied to variables, methods, blocks, and nested classes. When a member (variable or method) is declared as static
, it belongs to the class rather than any specific instance of the class. This means a static member can be accessed without creating an instance of the class.
Static members are shared among all instances of the class. This is particularly useful when you want to maintain a common property or utility method that should not be tied to individual object instances.
Below is an example demonstrating the static keyword:
public class Example {
static int staticCount = 0; // Static variable
Example() {
staticCount++; // Incrementing static variable in the constructor
}
static void displayCount() { // Static method
System.out.println("Count: " + staticCount);
}
public static void main(String[] args) {
Example obj1 = new Example();
Example obj2 = new Example();
Example.displayCount(); // Output will be: Count: 2
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?