Java Static Method, Variable and Block with Example
Lets learn the nuances of the static keywords by doing some excercises!
Example: How to call static variables & methods
Step 1) Copy the following code into a editor
Step 2) Save & Compile the code. Run the code as, java Demo.
Step 3) Expected output show below
Following diagram shows, how reference variables & objects are created and static variables are accessed by the different instances.
Step 4) It is possible to access a static variable from outside the class using the syntax ClassName.Variable_Name. Uncomment line # 7 & 8 . Save , Compile & Run . Observe the output.
A static block helps to initialize the static data members, just like constructors help to initialize instance members
Following program is the example of java static block.
Example: How to access static block