Communiquez avec les autres et partagez vos connaissances professionnelles

Inscrivez-vous ou connectez-vous pour rejoindre votre communauté professionnelle.

Suivre

Why we use static and init block in java?

user-image
Question ajoutée par Sandeep Singh Sandy , intern , itech power
Date de publication: 2013/10/17
Ashok Yadav
par 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
par 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
par 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