Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

Why we use static and init block in java?

user-image
Question added by Sandeep Singh Sandy , intern , itech power
Date Posted: 2013/10/17
Ashok Yadav
by Ashok Yadav , trainee , S.O Infotech Pvt. Ltd.

static blocks are those which runs whenever that class is loaded. these blocks are used to perform an action which we want to run when a class is loaded. for eg when we want to show a msg on class load we put the msg in static block.

 

init block are those which run whenever an object is created. These blocks are used when we want some task to run whenever an object is created. init blocks always run before the constructor

Basanta Kumar Dash SAMEER
by Basanta Kumar Dash SAMEER , Lecturer , CIITM

If we want to run a block before the execution of main method then we are using static method..

when we want run an object during its object creation then we are using init block.

 

Mohamed Zakarya
by Mohamed Zakarya , Training Manager , New Horizons Cairo

in order to initialize the values of static variable while the class loader loads the class and before reaching the runtime phase. becuase you want the value to be avilable for all objects before the objects are created.

More Questions Like This

Do you need help in adding the right keywords to your CV? Let our CV writing experts help you.