Tuesday, 3 July 2012

How static block works in Java


Static block and its description in Java

Static Block in Java:

In java, static is a keyword. All static stuffs(static variable, static method) belong to the class and not to the object(instance). Before going to static block, let's discuss about some static stuffs.


Static variables are basically class variables. When you define a static variable for your class implementation, there will be only one copy of the variable for the class rather than one for each instance of the class. They can be accessed without creating an instance of the class.

Static methods also called class methods and can be accessed without creating an instance of the class and like static variables, static methods will be accessed without instantiating the class .

Ex:
public class Test
    {
    static int foo = 12345;        
     static void TestMethod()
                {
               foo++;
                        }
 public static void main(String arge[])
 {
 System.out.println(foo);          //directly accessed  o/p:12345
 TestMethod();                    // directly accessed
 System.out.println(foo);        // o/p : 12346
 }
    
    }

Static blocks:

  1. Static blocks are also called Static initialization blocks .
  2. A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword.
    Ex :

    static {          // whatever code is needed for initialization goes here        }
  3. A class can have more then one static block in the class body.The run time system guarantees that static initialization blocks are called in the order that they appear in the source code.
  4. If you’re referring some static variables/methods from the static blocks, these statements will be executed after the class is loaded into JVM same as above i.e., now the static variables/methods referred and the static block both will be executed.

Ex:
public class Test
{
static int num;
static int res;
     static
            {
             num = 10;
             res = 12;
             System.out.println("I am static block, I am called first.");
             System.out.println("Result : "+(num*res));                              // o/p : 120
             past();                                                                                   // o/p : Method Block
     }
public static void main(String args[])
          {
          System.out.println("I am main() method, executed after static block.");
          System.out.println("Result : "+(num*res)); // o/p : 120
          }
static void past()
          {
          System.out.println("Method Block");
         }
}


O/P:

I am static block, I am called first.
Result : 120
Method Block
I am main() method, executed after static block.
Result : 120

 5. Static block can access instance variables (non-static variables) and instance methods by         creating an object of the class.

Ex :
public class Test
{
int num;
int res;
static Test T1;
    static
          {
          T1=new Test();
          T1.num = 10;
          T1.res = 12;
          System.out.println("I am static block, I am called first.");
          System.out.println("Result : "+(T1.num*T1.res));                      // o/p : 120
          T1.past();                          // call to concrete method ,   o/p : Method Block
  }

public static void main(String args[])
{
System.out.println("I am main() method, executed after static block.");
}
void past()
    {
     System.out.println("Method Block");
    }
}


O/p :
I am static block, I am called first.
Result : 120
Method Block
I am main() method, executed after static block.

Advantages of static blocks

  • If you’re loading drivers and other items into the namespace. (for instance Class.forName(”org.h2.Driver”)).
  • Initialize your static members at once ,as static block run once in the program execution.
  • Limitations for static blocks
  • You cannot throw Checked Exceptions.
  • “this” keyword can not be used since there is no instance.
  • You shouldn’t try to access super since there is no such a thing for static blocks.
  • You should not return anything from this block.


Non-Static Block/ constructor block

  • if we remove static keyword from static block/ initialization block, then it said to be non-Static block / constructor block.
  • This block is executed when the class is instantiated.
  • How many time your class get instantiated, constructor block/ non-Static block will called each time. That means constructor block will be copied into each constructor of the class.


Here is an Example :

public class NonStaticBlock{
{
System.out.println("First Non Static block");
}

public NonStaticBlock(){
System.out.println("This is no parameter constructor");
}

public NonStaticBlock(String param1){
System.out.println("This is single parameter constructor");
}

public NonStaticBlock(String param1, String param2){
System.out.println("This is two parameters constructor");
}

{
System.out.println("Second Non Static block");
}

public static void main(String[] args){
NonStaticBlock nonStaticEx = new NonStaticBlock();
NonStaticBlock nonStaticEx1 = new NonStaticBlock("java");
NonStaticBlock nonStaticEx2 = new NonStaticBlock("java", "oracle");
}
}

O/P will be like this:
First Non Static block                                 // coming from first constructor block
Second Non Static block                          // coming from second constructor block
This is no parameter constructor              // First instance created & constructor called
First Non Static block
Second Non Static block
This is single parameter constructor
First Non Static block
Second Non Static block
This is two parameters constructor