Static Block Demystified

  • 0
     Static keyword in Java has unusual properties. A variable flagged as static acts like a global variable, a class maintains a single copy of the static variables in the memory which is shared by all the class instances or objects of that class. A method tagged as static can be called without the creation of class object at first. Being a static method also puts some restrictions on the method, for example, it can only access static variables, can call only static methods and can not refer to "this" or "super" keyword in any way. In this article, I will try to clear some concepts regarding Static Block.

     When a class is first loaded into memory, all the static statements are run. This means that all the static declarations are allotted values.
     After this, the static block of the class is called. A block with the identifier static is called static block. After this, if the program is programmed to call a static method is called. However, logically, it seems that it should be the static method should be called, it is not the case.
     Another, pint is when a java source file has two class definition it it, actually, source file does not needs to contain so much stuff. By default, one can call the class of same class. So, if in another class, another static block is there, it is called when the program tries to create an object for it.
     After the execution of the static block, constructor of the class is called. Here is the program that proves all this.

package ClassIllustration;

class StaticTest
{
 static int first = 5;
 static int second;
 int third;
 
 StaticTest()
 {
  third = 3;
  
  System.out.println("In the constructor");
  System.out.println("Value of third is " + third);
 }
 
 static
 {
  System.out.println("In the static block of class StaticTest");
  second = first * second;
  
  System.out.println("Value of first and second is " +first +" and " + second);
 }
 
 static void StaticMethod()
 {
  second = 4;
  System.out.println("Static Method and value of second is " + second);
 }
 
}
class Static
{
 static
 {
  System.out.println("Static Block of class Static");
 }
 
 public static void main(String args[])
 {
  StaticTest.StaticMethod();
  
  StaticTest st = new StaticTest();

 }
}
To compile the program
javac -d . Static.java
And to run the program
java ClassIllustration.Static
Here is the output that I received
Static Block of class Static
In the static block of class StaticTest
Value of first and second is 5 and 0
Static Method and value of second is 4
In the constructor
Value of third is 3
As you can see, in the output, Static method of the class containing main method is called first. After this, Static block of the class StaticTest is called. Then according to calling sequence, StaticMethod() and then Constuctor of StaticTest is called.

No comments:

Post a Comment