In Java, the static
keyword is primarily used for memory management. It can be applied to variables, methods, blocks, and nested classes. During the JVM class loading process, JVM class loader subsystem first looks for static members and executes static blocks and initialise static variables as part of the class initialisation stage (learn more on Initialisation).
Static variable
Static variable also known as class variable, it is shared among all instances of the class. They are initialised only once when the class is loaded to the memory and stored in the JVM method area.
1
2
Static method
Static method is belong to a class rather than the instances of the class. They can be called without creating an instance of the class. Static methods can access static variables and methods directly but cannot access instance variables and methods directly.
Important
1
To access non-static variable in static method, use dependency injection or static dependency. Dependency injection
Static dependency
Static block
Code inside a static block is executed only only once when the class is first loaded by JVM. It is often used to initialise static members.
Note
The static blocks are executed before main method invocation. This is discussed in the JVM class loader subsystem.
Static block initialised.
10
Static nested class
A static nested class or static inner class is defined inside another class.
- Different from normal nested class, static nested class can be instantiated without the instance of the outer class.
- A static nested class can access static members of the outer class, including private.
- A non-static nested class has full access to the members of the class within which it is nested. A static nested class does not have a reference to a nesting instance, so a static nested class cannot invoke non-static methods or access non-static fields of an instance of the class within which it is nested.
Outer static variable: 100
To access the instance variable of the outer class, you have to instantiate the outer class object.
Back to parent page: Java Standard Edition (Java SE) and Java Programming
Web_and_App_DevelopmentProgramming_LanguagesJavaStaticStatic_MethodStatic_VariableStatic_BlockStatic_Nested_ClassNestedClass