Suppose one day, you want to find a job, such as the interview invitation, came to the interview company, finished the pen test, ushered in the interviewer.

The interviewer’s first question is: How do you prove in a piece of code that loading classes in the JVM is lazy?

Come on, sit down, take a look at this code, think about the results.

public class SuperClass { static { System.out.println("SuperClass init"); } public static int value = 10; } class SubClass extends SuperClass { static { System.out.println("SubClass init"); } } class TestClass { public static void main(String[] args) { System.out.println(SubClass.value); }} Only: SuperClass init10Copy the code

“SubClass init” is not printed. For static fields, only the class that directly defines the field is initialized, so referring to a static field defined in a parent class by its SubClass only triggers initialization of the parent class, not the child class.

So we can prove that the JVM is loading classes lazily, and let’s look at other cases.

Public initialization {public static void main(String[] args) {// SuperClass reference SuperClass[] superClasses = new SuperClass[10]; }} This code creates an array of reference types. Will the SuperClass be initialized?Copy the code

“Oh, this is all new, must be initialized ~ ~”

The answer is no, no, no

One last piece of code, would a Static block of Stataic code in a ConstClass be executed?

public class ConstClass { static { System.out.println("ConstClass init"); } public static final String HELLOWORLD = "hello world"; } class ConstTest { public static void main(String[] args) { System.out.println(ConstClass.HELLOWORLD); }}Copy the code

This is because, although ConstClass constants are referenced in Java code, the Hello world is stored in the constant pool of the NotInitialization class at compile time. So the reference to the HELLOWORLD constant points to the NotIntialization constant pool.