Why static block is exceuted first? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
16th Nov 2019, 12:35 PM
meena balasundaram
meena balasundaram - avatar
2 Answers
+ 2
Because java has something called static initializer block which can be used to initialize the instance variables of a class if at all they are not initialized. It can also do other stuffs as well like printing something to the screen etc. The static block runs before the main method so that everything is loaded and is ready before you go inside your main method and start program execution.
16th Nov 2019, 12:51 PM
Avinesh
Avinesh - avatar
0
I think this article helps you: https://www.scientecheasy.com/2018/09/static-block-java-example-advantage.html?m=1 "During the dot class file loading into memory, the static blocks are executed. After the loading dot class file, JVM calls the main method to start execution. Therefore, static block is executed before the main method. In other words, we can also say that Static block always gets executed first in Java because they are stored in the memory at the time of class loading or before the object creation." Here is a code about the execution order: https://code.sololearn.com/cRKxAwr2rE6t/?ref=app
18th Nov 2019, 10:39 AM
Denise Roßberg
Denise Roßberg - avatar