SKG SKG - 1 year ago 80
Java Question

When do we say class is loaded in java?

What does it mean when we say a

is "loaded"?

For example it is said that
Static init
blocks are executed at the time of class loading. When exactly
is loaded?

Please see this code from Kathy Sierra's book:

class Bird {
System.out.print("b1 ");
public Bird() {
System.out.print("b2 ");

class Raptor extends Bird {
static {
System.out.print("r1 ");
public Raptor() {
System.out.print("r2 ");
System.out.print("r3 ");
static {
System.out.print("r4 ");

class Hawk extends Raptor {
public static void main(String[] args) {
System.out.print("pre "); //1
new Hawk();//2
System.out.println("hawk ");

The output of above code is: r1 r4 pre b1 b2 r3 r2 hawk

I cant not understand howcome pre is printed after r1. Which part of the code loaded Raptor class?

One of the answer says :

"the class is initialized at the last possible moment, but before any of its members is accessed".

But by that logic, shouldn't pre be printed BEFORE r1? Since line 2 accesses constructor of class Raptor AFTER execution of line1.

Answer Source

Don't confuse class loading, which is implementation-specific, and class initialization, which is very strictly specified. Unfortunately these two terms are often used as if they meant the same thing, but usually the phrase "the time of class loading" refers to the time of class initialization.

As an executive summary of the detailed case-by-case rules, the class is initialized at the last possible moment, but before any of its members is accessed.

With that part cleared up, in the code of your example you have a class Hawk extends Raptor extends Bird. Hawk is the class containing the entry point of your program, the method main. This is the init order:

  1. Start initializing Hawk. Is its parent class Raptor initialized? no.
  2. Start initializing Raptor. Is its parent Bird initialized? no.
  3. Start initializing Bird.
  4. Complete initializing Bird.
  5. Execute Raptor's static init blocks. This prints r1 r4.
  6. Complete initializing Raptor.
  7. Complete initializing Hawk.
  8. Start executing Hawk.main(). This prints pre.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download