Wednesday, September 24, 2014

[Java][Tutorial] Initializer initialization block, and Static Initialization Block



Initializer

An initializer is a line of code (or a block of code) placed outside any method, constructor, or other block of code. Initializers are executed whenever an instance of a class is created, regardless of which constructor is used to create the instance. This is the simplest example of initializer:
class Class2{
    public int y= 0;
}


Initialization Blocks

Initializer can also be a block of code , it’s enclosed in braces, { }. Let’s have a look of an example from dummies.com:
class PrimeClass
{
    private Scanner sc = new Scanner(System.in);
    public int x;
    {
        System.out.print(
            "Enter the starting value for x: ");
        x = sc.nextInt();
    }
}

Since code of an initialization block is copied into the beginning of each constructor of the class. If you have many constructor in your class and want run some common code at their beginning. You can put it into a initialization block so that can write the code once only:

public class JavaApplication1{
    char inputChar;
    JavaApplication1(){System.out.println("c");}
    JavaApplication1(char inputChar) {System.out.println(inputChar);}
    {System.out.println("This is code in Initialization Block.");}
   
    public static void main(String[] args) {
        new JavaApplication1();
        new JavaApplication1('i');
    }
}
And the result is : 


This is code in Initialization Block.
c
This is code in Initialization Block.
I


 
 

Static Initialization Blocks

A static initialization block is a normal block of code enclosed in braces, { }, with the keyword in front of theblock. It includes variable declarations with initializers.
A block of Static Initialization Blocks runs only once, and it is run the first time the Constructor or the main() method for that class is called.

import java.util.*;
public class JavaApplication1{  
    public static void main(String[] args) {
        new JavaApplication1().test();
        new JavaApplication1().test();
    }
   
    void test(){
        System.out.println("This is a method.");
    }
    static {System.out.println("This is a Static Initialization Block");}
}

Result:

This is a Static Initialization Block
This is a method.
This is a method.




For some advanced example, you can reference from an example about the Initialization Block:

Referenced link:

No comments :

Post a Comment