What is static initializer block in java ?

Before we learn about the static initializer block in java we must familiar with basic programming language like C/C++.
To know the power of java programming language, I would like to give you a problem, try to make a solution for it. The problem is that to make a program in which make a class whose name is Account which has four data members
1)AccountId  (Should be an integer)
2)Account_holder_name (Should be a char array or String)
3)bank_balance(Should be an integer)
4)rate_of_interest (It should be an integer and also it will be same for all the account holders)

And then write a program to display the AccountId and name of the account holder and also display his bank balance and rate of interest provided by a bank but the challenge is that to make a program in such a way that the static data member (rate_of_interest) initialized only once. If we create a constructor in our class then it will be called until the different object is created. It can be solved but we cannot short out this problem easily.
 
                               But in java, we can easily solve this problem just by making use of static initializer blocks.


Definition:-
               In java, static blocks are those special blocks which are automatically executed by java whenever we make first use of the class. The word first use means two thinks:-
     1.  Creating the first object of a class.
   2.   Accessing a static member of the class for the first time.

A static block is always executed only once and can only access static data of the class.

Program in java which can help you to easily understand this topic:-


class Account {
private int accid;
private String name;
private int bal;
private static int rate_of_int;
public Account(int accid,String name,int bal)
{
   this.accid=accid;
   this.name=name;
   this.bal=bal;
}
static
{
rate_of_int=10;
}
public void display()
{
   System.out.println("Account Id is:"+accid);
   System.out.println("Name is:"+name);
   System.out.println("balance is:"+bal);
   System.out.println("Rate of interest is:"+rate_of_int);

}
 }
class UseAccount {
    public static void main(String[] args) {
        Account obj=new Account(101,"Shubham",35000);
        obj.display();
        
    }   
}
 
In the above program, the rate_of_nterest is initialized only once. I hope you guys you liked this post. If you have any query related on this topic then comment me on the comment section.

                  * Thank you* 

Comments