![]() |
VOOZH | about |
The static keyword in Java is used for memory management and belongs to the class rather than any specific instance. It allows members (variables, methods, blocks, and nested classes) to be shared among all objects of a class.
The static keyword can be applied to four main components:
A static variable is also known as a class variable. It is shared among all instances of the class and is used to store data that should be common for all objects.
101 Ravi GFG 102 Amit GFG
A static block is executed only once when the class is first loaded into memory. It is often used to initialize static variables or perform configuration tasks before the main method executes.
Static block initialized. from main Value of a : 10 Value of b : 40
A static method belongs to the class rather than to any object. It can be called directly using the class name.
From m1 Inside static block Value of a: 20 From main
A static nested class is a class declared as static inside another class. It can be accessed without creating an object of the outer class.
Static Nested Class Method
Note: The Inner class is accessed using the outer class name (Outer.Inner).
The table below demonstrates the difference between Static and Non-Static
| Aspect | Static | Non-Static |
|---|---|---|
| Belongs To | Class (shared by all objects) | Individual object (unique per instance) |
| Memory Allocation | Created once when class is loaded | Created separately for each object |
| Access Method | Accessed using class name | Accessed using object reference |
| Can Access | Only other static members directly | Both static and non-static members |
| Common Use | Utility methods, constants, shared data | Object-specific data and behavior |