What is static keyword in Java?

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 } }

static keyword Java static variables Java static methods memory management in Java Java programming