"Hello, Amigo! I heard Rishi explained something new and exciting to you?!"
"That's right, Kim."
"My topic will be no less interesting. I want to tell you about how classes are loaded into memory."
Classes in Java are files on the disk that contain bytecode, which is compiled Java code.
"Yes, I remember."
The Java machine doesn't load them if it doesn't need to. As soon as there's a call to a class somewhere in the code, the Java machine checks to see if it is loaded. And if not, then it loads and initializes it.
Initializing a class involves assigning values to all of its static variables and calling all static initialization blocks.
"That seems similar to calling a constructor on an object. But what's a static initialization block?"
"If you need to execute complex code (for example, loading something from a file) to initialize objects, we can do it in a constructor. However, static variables don't have this opportunity. But since the need still remains, you can add a static initialization block or blocks to classes. They are basically equivalent to static constructors."
This is how it looks:
Code | What really happens |
---|---|
|
|
It's a lot like what happens when a constructor is called. I've even written it as a (nonexistent) static constructor.
"Yes, I get it."
"Very good."
GO TO FULL VERSION