The favourite interview question one of my friends used to ask was what happens when a java program is run. The answer to this question would set our expectations from the guy in front of us immediately. Most did not even get close.
So what is the answer?
Three important steps happen before main is invoked - loading, linking and initialization.
Loading
- Loads the class byte codes and create a Class object.
- verification - binary representation of a class or interface is structurally correct
- preparation - creating the static fields for a class or interface and initializing such fields to the default values
- resolution -symbolic references to other classes and interfaces and their fields, methods, and constructors is checked to be correct and, typically, replaced with a direct reference that can be more efficiently processed if the reference is used repeatedly
- Initialization of a class consists of executing its static initializers and the initializers for static fields
- Initialization of an interface consists of executing the initializers for fields (constants) declared
- Synchronize on the Class object that represents the class or interface to be initialized since other threads may be attempting to init the same class.
No comments:
Post a Comment