Why Static and Non-sSatic(instance) Blocks are executed before Constructor?

 As we know Compiler converts .java files into .class files, as we can see from image below. .class files 

contain Bytecodes which are used by machine.


JVM-Java Virtual Machine operates on RAM(Random Access Memory). JVM requires .class files and 

and inside JVM there are Class Loader, Byte Code Verifier and Execution Engine. Class loader reads .class

files and understand its content thus could distribute static and instance variables and methods to a specific 

memory. Execution Engine (JIT-just in time) converst bytecode into machine code.


However we didn't answer yet the core question. Why Blocks are executed before the Constructor. 
Static fields are downloaded first and ready for execution. And the purpose of any Constructor to set any value or call any Static field of a class. Thus, imagine Class Loader doesn't load static field, and how Constructor is able to set any value or call any method(behavior)? 
This is like I(Parvin) want anybody(let it be John) to handle 500 $ to anyone(Chris). First of all Chris has to 
be there and has to be aware about the amount of money which I am going to handle him. And imagine I give the money to John to deliver Chris, and Chris is not in the place or doesn't know about the amount of money. 
So I guess You understand why Static and Non-Static(instance) Blocks are executed first.
It is pretty easy now yes?
Let me summarize. 1.Class loader reads and understands the content of the class. 2.It separates static and instance variables and methods. 3.When we create an object for example User u = new User(5);  The program reads it from left to right and understands that we want to create a User object. And then Class loader reads its content and understands that static and non-static fields should be prepared before execution.
First Static Fields and then Static Block, then Instance Fields and then Instance Block. Then the program sees new User(5). It understands that we want to call constructor and set a value. That is why Block are executed before Constructor. 

Комментарии

Популярные сообщения из этого блога

IoC:ApplicationContext, BeanFactory. Bean

Lesson1: JDK, JVM, JRE

Lesson_2: Operations in Java