Static Block

<< Previous Chapter Next Chapter >>
Static Block In Java:

A static block is similar to the init block with with few differences. A static block executes only once at the time of class loading. Let’s take a scenario where I want to initialize my static data members dynamically. In a simple java program there is no place which ensures one time execution during class loading, we have main() method but this method executes after class is loaded. So, to overcome this problem, the static block is introduced.

Example:
Let’s take a simple example which initializes the static data members dynamically.

class Temp
{
      static int x;
     
      static{
            try{
                  System.out.println("Executing Static Block: Please enter any number: ");
                  x = System.in.read();
            }
            catch(Exception e)
            {
                  e.printStackTrace();
            }
      }

      Temp()
      {
            System.out.println("Default constructor executed.");
      }
     
      Temp(int x)
      {
            System.out.println("Parameterized constructor executed.");
      }
      public static void main(String args[])
      {
            Temp temp1 = new Temp();
            Temp temp2 = new Temp(20);
            System.out.println("x = " + Temp.x);
      }
     
}


Output:
Executing Static Block: Please enter any number: 90
Default constructor executed.
Parameterized constructor executed.
x = 57


Let’s take another example of static block:

Temp.java

class Temp
{
      static Demo d;
     
      static{
            d = new Demo();
      }
}

Demo.java

public class Demo
{
      void show (int x)
      {
            System.out.println("x = " + x);
      }
     
      public static void main(String args[])
      {
            Temp.d.show(20);
      }
}


Output:
x = 20

in above example Temp.d.show(20)  is equivalent to famous System.out.println(20), So System.out.println is internally implemented in this way.


<< Previous Chapter Next Chapter >>




No comments:

Post a Comment