Static variable

Java Static Method, Variable and Block with Example

Let’s look at static variables and static methods first.

What is Static Variable in Java?

Static variable in Java is variable which belongs to the class and initialized only once at the start of the execution.

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

Java Static Methods and Variables 

Following diagram shows, how reference variables & objects are created and static variables are accessed by the different instances.

Java Static Methods and Variables 

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.

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